http.FileServer 可直接提供静态资源服务,需用 filepath.Abs 转绝对路径防部署异常;默认不支持目录列表和 index.html 自动查找,须手动注册根路由;其内置安全过滤可防路径穿越,但需注意权限与 MIME 类型扩展。

go 标准库的 http.FileServer 足够胜任大多数静态资源服务场景,无需额外框架或中间件。
用 http.FileServer 快速启动一个静态文件服务器
这是最轻量、最直接的方式。关键在于正确构造 http.Filesystem,避免路径穿越漏洞和 404 错误。
- 必须用
http.Dir指向**绝对路径**,相对路径在不同工作目录下行为不一致 - 推荐用
filepath.Abs显式转为绝对路径,防止部署时出错 - 默认不支持目录列表(即访问
/返回 404),如需开启,需额外包装
package main import ( "net/http" "path/filepath" ) func main() { dir, _ := filepath.Abs("./public") fs := http.FileServer(http.Dir(dir)) http.Handle("/Static/", http.StripPrefix("/static/", fs)) http.ListenAndServe(":8080", nil) }
上面代码把 ./public 映射到 /static/ 路径下,比如请求 /static/js/app.js 会读取 ./public/js/app.js。
处理根路径访问(/)和默认首页
http.FileServer 默认不自动查找 index.html,访问 / 会返回 404,除非你显式注册。
立即学习“go语言免费学习笔记(深入)”;
- 若希望
/返回index.html,不要依赖FileServer自动行为 - 更可靠的做法是单独注册
GET /路由,用http.ServeFile指定文件 - 如果想让整个根路径都走静态服务且带 index 支持,可用
http.ServeMux组合实现
func main() { dir, _ := filepath.Abs("./public") fs := http.FileServer(http.Dir(dir)) mux := http.NewServeMux() mux.Handle("/static/", http.StripPrefix("/static/", fs)) // 根路径:优先尝试 serve index.html mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { http.ServeFile(w, r, filepath.Join(dir, "index.html")) return } fs.ServeHTTP(w, r) }) http.ListenAndServe(":8080", mux) }
常见陷阱:路径穿越、权限错误与 MIME 类型
看似简单的静态服务,实际容易因路径或配置出问题:
-
http.Dir不做路径净化,若用户构造..请求(如/static/../etc/passwd),可能越权读取——但http.FileServer内部已做了安全过滤,只要不用自定义FileSystem就基本安全 - linux 下注意文件权限:Go 进程需有读取目标目录的权限,否则返回 403;windows 一般无此问题
- MIME 类型由
http.ServeContent自动推断,但小众后缀(如.webp、.wasm)可能识别失败,可提前调用mime.AddExtensionType
import "mime" func init() { mime.AddExtensionType(".webp", "image/webp") mime.AddExtensionType(".wasm", "application/wasm") }
真正需要小心的是多层嵌套路径映射、跨模块资源复用,以及调试时工作目录和构建路径不一致导致的 file not found —— 建议所有路径初始化阶段就打印 filepath.Abs 结果用于验证。