Go http.FileServer始终为404';当文件存在时,单击“s”
初学者围棋问题 我有这个目录结构Go http.FileServer始终为404';当文件存在时,单击“s”,go,Go,初学者围棋问题 我有这个目录结构 app_executable html | - index.html data | - static_file.json 我无法让它为data/static\u file.json中的static\u file.json提供服务 func main() { // this works and serves html/index.html html := http.FileServer(http.Dir("html")) http.Han
app_executable
html
|
- index.html
data
|
- static_file.json
我无法让它为data/static\u file.json
中的static\u file.json
提供服务
func main() {
// this works and serves html/index.html
html := http.FileServer(http.Dir("html"))
http.Handle("/", html)
// this always 404's
data := http.FileServer(http.Dir("data"))
http.Handle("/data/", data)
fmt.Println("Listening on port " + port + "...")
log.Fatal(http.ListenAndServe(port, nil))
}
感谢您的帮助 问题在于,文件服务器处理程序实际上正在该路径上查找文件:
./data/data/static_file.json
而不是
./data/statif_file.json
如果您使第一个文件存在,代码将正常工作。您可能想做的是:
data := http.FileServer(http.Dir("data"))
http.Handle("/", data)
或
我会选择前者,因为这可能是你真正想做的。将处理程序附加到根目录,任何与/data/匹配的内容都将按预期返回
如果您查看对的调用实际返回的内容
data := http.FileServer(http.Dir("data"))
你会看到的
&http.fileHandler{root:"data"}
这意味着根目录位于./data,因此请尝试在该根目录下查找与请求路径匹配的文件。在您的例子中,路径是data/static_file.json,因此它最终会检查不存在的./data/data/static_file.json,并且它是404
&http.fileHandler{root:"data"}