我正在学习 Go,但在使用我的服务器提供静态文件时遇到问题。我总是得到 404。
该请求针对http://localhost:3001/static/breakfast.jpg
路由器+文件服务r
mux := chi.NewRouter()
mux.Get("/", handlers.Repo.Home)
fileServer := http.FileServer(http.Dir("./static/"))
mux.Handle("/static/*", http.StripPrefix("/static", fileServer))
静态文件路径
root/static/
我的模板 homepage.tmpl
{{template "base" .}}
{{define "content"}}
<div class="container">
<div class="row">
<div class="col">
<h1>Hi from home page</h1>
<img src="/static/breakfast.jpg" width="1920" height="1080" alt="house" />
</div>
</div>
</div>
{{ end }}
我做错了什么?
最佳答案
这个source告诉 http.Dir
从运行 main.go
文件的目录相对地提供文件。如果您传递绝对路径,那么它与此无关,并且只需阅读代码就更容易理解:
http.Dir("/static/")
(因为这是您的情况下文件系统上的绝对路径)。
请注意 http.Dir
的一些警告,如所述 here :
(即它的目录分隔符与操作系统相关,该方法可以遵循危险的符号链接(symbolic link),并且可以列出以点开头的文件并暴露敏感目录,例如 .git
)
关于go - 如何使用 Go Chi 提供静态文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72736418/