在Go中提供静态文件时,是否需要使用http.StripPrefix?

huangapple go评论80阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年6月3日 14:50:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/44341203.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定