任务:
我尝试使用 Golang 提供静态文件。
问题:
显示了目录内容,但未找到目录中的文件。
项目结构:
projectdir/
|- main.go
|- static/
|- main.css
|- templates
|- index.tmpl
源代码片段:
main.go
func serv() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
srv := &http.Server{
Handler: r,
Addr: "127.0.0.1:8666",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
问题描述
如果我启动程序并将浏览器指向 127.0.0.1:8666/static/,则会列出目录 ./static 的内容,即 main.css
如果我单击文件 main.css,服务器响应为 404。
问题
我错过了什么?
提前致谢!
最佳答案
Gorilla 路由器与 Go 的不同,Gorilla 只会匹配给定的确切 URL,而不仅仅是 URL 前缀。 Gorilla documentation对此进行了更详细的解释。 ,其中解释了如何 PathPrefix
可用于提供文件:
r.PathPrefix("/static/").
Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
关于go - 使用 Go 提供静态文件会出现 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50447575/