英文:
Cannot serve static files in a Go Gorilla server
问题
我正在使用一个小型玩具服务器来学习Go Web编程。
我的项目目录结构中有一个名为public
的目录:
public\
| style.css
public
和style.css
的权限对于所有人都是r-x
和r--
。
在main.go
中,我有以下代码:
router := mux.NewRouter()
router.Handle("/static/",
http.StripPrefix("/static/", http.FileServer(http.Dir("public"))))
log.Fatal(http.ListenAndServe(":3001", router))
每次我访问http://localhost:3001/static/style.css
时,服务器都返回404错误。
我尝试了路径中前导和尾随斜杠的所有组合,但没有任何区别。
我在Ubuntu 15.10 (x64)上运行Go v1.5.3。
英文:
I am playing with a small toy server to learn Go web programming.
My project directory structure has the following public
directory:
public\
| style.css
The permissions on public
and style.css
are r-x
and r--
for everyone.
In main.go
, I have the following lines:
router := mux.NewRouter()
router.Handle("/static/",
http.StripPrefix("/static/", http.FileServer(http.Dir("public"))))
log.Fatal(http.ListenAndServe(":3001", router))
Every time I call http://localhost:3001/static/style.css
the server returns a 404.
I have tried all combinations of leading and trailing slashes in the paths, but none make any difference.
I am running Go v1.5.3 on Ubuntu 15.10 (x64).
答案1
得分: 4
以下是你要翻译的内容:
这是一个示例,演示如何从名为public
的文件夹中为/static/
下的任何请求提供服务。
router := mux.NewRouter()
//router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("public"))))
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("public/"))))
log.Fatal(http.ListenAndServe(":3001", router))
英文:
Here's an example of how you can serve any requests to a file in /static/
from a folder called public
.
router := mux.NewRouter()
//router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("public"))))
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("public/"))))
log.Fatal(http.ListenAndServe(":3001", router))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论