使用http.FileServer与embed服务静态文件时出现404错误的问题
解决embed结合http.FileServer与Gorilla Mux返回404的问题
你的代码存在两个关键问题,导致请求静态文件时返回404:
1. 路由匹配方式错误
Gorilla Mux的Handle方法默认是精确路径匹配,无法覆盖所有/static/开头的子路径(比如/static/style.css)。需要改用PathPrefix来匹配所有以指定前缀开头的请求。
2. 前缀剥离参数不匹配
原代码中http.StripPrefix("/static", server)会将/static/style.css剥离为/style.css,但通过fs.Sub得到的assets文件系统是static目录的内容(文件直接是style.css,没有开头斜杠),因此FileServer会查找不存在的/style.css,导致404。需将剥离参数改为/static/,剥离后得到style.css才能正确匹配文件。
修正后的代码
package main import ( "embed" "github.com/gorilla/mux" "io/fs" "log" "net/http" ) //go:embed static var css embed.FS func main() { assets, err := fs.Sub(css, "static") if err != nil { log.Fatal(err) // 新增错误处理,避免隐性问题 } server := http.FileServer(http.FS(assets)) router := mux.NewRouter() // 使用PathPrefix匹配前缀路径,修正StripPrefix参数 router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", server)) err = http.ListenAndServe(":8080", router) log.Fatal(err) }
额外注意事项
- 确保项目目录结构正确:
static目录需与main.go处于同一层级,且目录内存在目标CSS文件(如static/style.css)。 - 不要忽略
fs.Sub的错误:原代码忽略错误可能导致后续逻辑在目录异常时静默失败,新增错误处理能及时排查问题。
内容的提问来源于stack exchange,提问作者Crismar
相关产品推荐
相关产品推荐

