英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论