英文:
how to serve static files with http ? go
问题
我正在使用下面的代码片段:
fa := http.FileServer(http.Dir("attach/"))
http.Handle("/attach", fa)
文件位于 /attach/
目录中。然而,当我访问 localhost/attach
或 localhost/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 /.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论