how to serve static files with http ? go

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

how to serve static files with http ? go

问题

我正在使用下面的代码片段:

fa := http.FileServer(http.Dir("attach/"))
http.Handle("/attach", fa)

文件位于 /attach/ 目录中。然而,当我访问 localhost/attachlocalhost/attach/anyfile 时,它会抛出“未找到”错误。

英文:

I'm using the snippet below:

fa := http.FileServer(http.Dir("attach/"))
http.Handle("/attach", fa)

The files are located into /attach/ directory. However when I hit localhost/attach or localhost/attach/anyfile it throws not found error

答案1

得分: 3

FileServer处理程序从根目录提供目录内容,但处理程序从请求中接收到完整路径。如果你处理的路径不是/,你需要去掉该前缀。

fa := http.FileServer(http.Dir("/attach"))
http.Handle("/attach/", http.StripPrefix("/attach/", fa))

更多信息请参考:http://golang.org/pkg/net/http/#example_FileServer_stripPrefix

英文:

The FileServer handler serves the directory content from root, but the handler receives the full path from the request. If you are handling at a path other than /, you need to strip that prefix off.

fa := http.FileServer(http.Dir("/attach"))
http.Handle("/attach/", http.StripPrefix("/attach/", fa))

http://golang.org/pkg/net/http/#example_FileServer_stripPrefix

答案2

得分: 0

如果文件位于/attach目录下,那么在使用http.Dir()时,路径名是错误的,除非当前目录是/。

英文:

If the files are located under /attach then the pathname used with http.Dir() is wrong, unless the current directoy is /.

huangapple
  • 本文由 发表于 2014年8月6日 08:07:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/25150292.html
匿名

发表评论

匿名网友

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

确定