我的项目结构如下:
/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的响应返回
发布于 2017-02-16 02:42:01
使用尾随斜杠注册文件处理程序,以指示要匹配子树。有关使用尾斜杠的更多信息,请参见文档。
http.Handle("/res/", serveFile)另外,使用句柄而不是HandleFunc。
提供索引文件是因为"/“匹配其他路径不匹配的所有路径。若要在这些情况下返回404,请将索引处理程序更新为:
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.
}https://stackoverflow.com/questions/42263791
复制相似问题