无法在Go Gorilla服务器中提供静态文件。

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

Cannot serve static files in a Go Gorilla server

问题

我正在使用一个小型玩具服务器来学习Go Web编程。

我的项目目录结构中有一个名为public的目录:

public\
  | style.css

publicstyle.css的权限对于所有人都是r-xr--

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))

huangapple
  • 本文由 发表于 2016年1月17日 03:00:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/34830888.html
匿名

发表评论

匿名网友

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

确定