http静态目录没有被提供服务。

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

http static directories aren't being served

问题

我不明白为什么我的静态资源没有被提供。这是代码:

func main() {
	http.HandleFunc("/", get_shows)
	http.HandleFunc("/get",  get_show_json)
	http.HandleFunc("/set", set_shows)
	http.Handle("/css/", http.FileServer(http.Dir("./css")))
	http.Handle("/js/", http.FileServer(http.Dir("./js")))
	http.ListenAndServe(":8080", nil)
}

当我运行程序时,导航到 http://myhost.fake/css/ 或者 http://myhost.fake/css/main.css(这些在文件系统中存在),我得到一个404错误。如果我用完整路径替换"./css",js静态目录也是一样。我的其他处理程序工作正常。我在linux上。谢谢!

英文:

I don't understand why my static resources aren't being served. Here is the code:

func main() {
	http.HandleFunc("/", get_shows)
	http.HandleFunc("/get",  get_show_json)
	http.HandleFunc("/set", set_shows)
	http.Handle("/css/", http.FileServer(http.Dir("./css")))
	http.Handle("/js/", http.FileServer(http.Dir("./js")))
	http.ListenAndServe(":8080", nil)
}

When I run the program, navigating to http://myhost.fake/css/ or to http://myhost.fake/css/main.css (these exists in the filesystem), I get a 404 error. The same is true if I replace "./css" with the full path to the directory. Ditto for the js static directory. My other handlers work fine. I am on a linux. Thanks!

答案1

得分: 13

你的处理程序路径(/css/)被传递给了FileServer处理程序以及前缀后的文件。
这意味着当你访问http://myhost.fake/css/test.css时,你的FileServer会尝试找到文件./css/css/test.css

http包提供了函数StripPrefix来去除/css/前缀。

这样做应该可以解决问题:

http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
英文:

Your handler path (/css/) is passed to the FileServer handler plus the file after the prefix.
That means when you visit http://myhost.fake/css/test.css your FileServer is trying to find the file ./css/css/test.css.

The http package provides the function StripPrefix to strip the /css/ prefix.

This should do it:

http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))

答案2

得分: 0

我现在无法验证,但是我记得:s/"./css"/"css"/; s/"./js"/"js"/

编辑:现在我终于可以检查源代码了:这是我所做的和对我有效的:

http.Handle("/scripts/", http.FileServer(http.Dir("")))
http.Handle("/images/", http.FileServer(http.Dir("")))

所有在./images/*.{gif,png,...}中的图片都可以正常显示。关于脚本也是同样的情况。

英文:

I cannot verify it now, but IIRC: s/"./css"/"css"/; s/"./js"/"js"/.

EDIT: Now that I can finally check the sources: This is what I did and what works for me:

http.Handle("/scripts/", http.FileServer(http.Dir("")))
http.Handle("/images/", http.FileServer(http.Dir("")))

All images in ./images/*.{gif,png,...} get served properly. The same story about scripts.

huangapple
  • 本文由 发表于 2013年3月20日 03:02:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/15508250.html
匿名

发表评论

匿名网友

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

确定