英文:
Fileserver() always returns index.html
问题
我的项目结构如下:
/rootfolder
index.html
main.js
main.go
我试图通过FileServer()来提供静态的javascript文件,但它总是返回index.html而不是main.js作为响应。
在main.go中:
serveFile := http.StripPrefix("/res/", http.FileServer(http.Dir(".")))
http.HandleFunc("/", indexHandler)
http.Handle("/res", serveFile)
http.ListenAndServe(":8080", nil)
在index.html中,main.js的引用如下:
<script src="/res/main.js"></script>
从浏览器的网络选项卡中可以看出,FileServer()总是将index.html文件作为对/res/main.js
的响应返回。
英文:
My project structure is as follows:
/rootfolder
index.html
main.js
main.go
I'm trying to serve the static javascript file through FileServer(), which always returns the index.html as a response instead of the main.js
In main.go:
serveFile := http.StripPrefix("/res/", http.FileServer(http.Dir(".")))
http.HandleFunc("/", indexHandler)
http.Handle("/res", serveFile)
http.ListenAndServe(":8080", nil)
Inside index.html main.js is referenced as follows:
<script src="/res/main.js"></script>
From the network tab in my browser, it appears that FileServer() is always returning the index.html file as a response to /res/main.js
答案1
得分: 2
将文件处理程序注册为带有斜杠的路径,以指示您希望匹配子树。有关斜杠的使用更多信息,请参阅文档。
http.Handle("/res/", serveFile)
此外,使用Handle
而不是HandleFunc
。
之前的索引文件被提供是因为"/"
匹配所有未被其他路径匹配的路径。要在这些情况下返回404,请更新索引处理程序:
func indexHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Not found", 404)
return
}
// ... 在此之前的任何代码。
}
英文:
Register the file handler with a trailing slash to indicate that you want to match the subtree. See the documentation for more info on the use of the trailing slash.
http.Handle("/res/", serveFile)
Also, use Handle instead of HandleFunc.
The index file was served because "/" matches all paths not matched by some other path. To return 404 in these cases, update the index handler to:
func indexHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Not found", 404)
return
}
... whatever code you had here before.
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论