Golang文件服务器抛出“未找到”错误。

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

Golang fileserver throws not found

问题

我正在尝试提供一些字体文件,但是当我访问localhost:4000/fonts时,它显示404未找到。我的代码如下:

fs := http.FileServer(http.Dir("./fonts"))

http.Handle("/fonts", http.StripPrefix("/fonts/", fs))

http.Handle("/", app.routes())

log.Println("Serving at localhost:4000...")
log.Fatal(http.ListenAndServe(fmt.Sprintf("localhost:%d", cfg.Port), nil))

更新:

如果我从"/"而不是"/fonts"进行服务,它可以工作。但是我希望它能从"/fonts"工作。

英文:

I am trying to serve some fonts, but when i visit localhost:4000/fonts, it gives me 404 not found. my code:


	fs := http.FileServer(http.Dir("./fonts"))

	http.Handle("/fonts", http.StripPrefix("/fonts/", fs))

	http.Handle("/", app.routes())

	log.Println("Serving at localhost:4000...")
	log.Fatal(http.ListenAndServe(fmt.Sprintf("localhost:%d", cfg.Port), nil))

UPDATE

if im serving from "/" and not "/fonts", it works. but i want it to work from "/fonts".

答案1

得分: 1

在字体之后,你不应该去掉尾部的斜杠,因为你希望结果是 /file 而不是 file

出于同样的原因,你还应该在处理程序路径后添加尾部的斜杠。

http.Handle("/fonts/", http.StripPrefix("/fonts", fs))

正如前面提到的,这两个更改的目的是让你得到一个像 /somefile 这样的路径,然后在文件服务器的文件系统中查找。

英文:

You should not strip the trailing slash after fonts since you want the result to be /file and not file.

You should also add the trailing slash to the handler path, for the same reason.

http.Handle("/fonts/", http.StripPrefix("/fonts", fs))

Both changes, as mentioned, have the purpose to leave you with a path like /somefile that is looked up against the filesevers file system.

huangapple
  • 本文由 发表于 2022年4月16日 18:26:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/71893075.html
匿名

发表评论

匿名网友

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

确定