英文:
How do I serve static files with Go Chi?
问题
我正在学习Go语言,但在使用服务器时遇到了一个问题,无法正确提供静态文件,总是返回404错误。
请求的URL是http://localhost:3001/static/breakfast.jpg
。
我使用了路由器和文件服务器。
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 }}
请问我做错了什么?
英文:
I'm learning Go and I'm having a trouble serving static files with my server. I always get 404.
The request is for http://localhost:3001/static/breakfast.jpg
Router + fileServer
mux := chi.NewRouter()
mux.Get("/", handlers.Repo.Home)
fileServer := http.FileServer(http.Dir("./static/"))
mux.Handle("/static/*", http.StripPrefix("/static", fileServer))
Static files path
root/static/
My template 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 }}
What am I doing wrong?
答案1
得分: 2
这个来源告诉我们,http.Dir
会相对于你运行main.go
文件的目录来提供文件。如果你传递绝对路径,那么它就与此无关,并且通过阅读代码更容易理解:
http.Dir("/static/")
(在你的情况下,这是文件系统上的绝对路径)。
请注意http.Dir
的一些注意事项,如这里所述:
(例如,它的目录分隔符取决于操作系统,该方法可能会遵循危险的符号链接,并且可能会列出以点开头的文件并公开敏感目录,如.git
)。
英文:
This source tells that http.Dir
serves the file relatively from the directory from which you run the main.go
file. If you pass the absolute path then it's independent from this and easier to understand by just reading the code:
http.Dir("/static/")
(since this is the absolute path on filesystem in your case).
Beware of some caveats with http.Dir
as stated here:
(i.e. its directory separator is os-dependent, the method can follow dangerous symlinks, and could list files beginning with a dot and expose sensitive directories like .git
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论