gpt4 book ai didi

go - Fileserver() 总是返回 index.html

转载 作者:IT王子 更新时间:2023-10-29 02:03:33 25 4
gpt4 key购买 nike

我的项目结构如下:

/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 的响应

最佳答案

用尾部斜杠注册文件处理程序以指示您要匹配子树。查看documentation有关使用尾部斜线的更多信息。

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
}
... whatever code you had here before.
}

关于go - Fileserver() 总是返回 index.html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com