英文:
Is http.StripPrefix necessary when serving static files in Go?
问题
http.Handle("/static/", http.FileServer(http.Dir("")))
这段代码有什么问题?
我找到的最简单的示例代码如下:
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.StripPrefix
是否必要?
英文:
What's wrong with http.Handle("/static/", http.FileServer(http.Dir("")))
?
The shortest example I can find looks like this:
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
Is http.StripPrefix
necessary?
答案1
得分: 4
不,这不是必需的,但如果你不使用它,用于查找文件的路径将包括前缀。通过一个例子来说明会更清楚,假设你的文件夹结构如下:
main.go
static/
styles.css
你可以使用以下代码来提供这些文件:
http.Handle("/static/", http.FileServer(http.Dir("")))
那么,用户请求yoursite.com/static/styles.css
将会得到static文件夹中的styles.css文件。但是,为了使其正常工作,你的路径必须完全匹配。
大多数人更喜欢使用以下方法:
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
这样,他们可以更改URL路径为/assets/
,而无需重命名static文件夹(或者反过来,改变本地目录结构而不更新URL路径)。
简而言之,路径前缀不是必需的,但可以用来打破URL路径和本地目录结构完全匹配的要求。
英文:
No it is not required, but if you DO NOT use it the path used to find the file will include the prefix. This is clearer with an example, so imagine your folder structure was:
main.go
static/
styles.css
And you serve the files with:
http.Handle("/static/", http.FileServer(http.Dir("")))
Then a user requesting the file at yoursite.com/static/styles.css
would get the styles.css file in the static dir. But for this to work your paths must line up perfectly.
Most people prefer to do the following instead:
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
Because they could change their URL path to be something like /assets/
without needing to rename the static dir (or vise versa - change the local dir structure w/out updating the URL path).
TL;DR - Path prefix isn't required but is useful to break any requirements of URL paths and local directory structure matching perfectly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论