英文:
http.FileServer always 404's when file exists
问题
初学者的Go问题
我有这样的目录结构。
app_executable
html
|
- index.html
data
|
- static_file.json
我无法让data/static_file.json
在服务器上提供。
func main() {
// 这个可以正常工作并提供html/index.html
html := http.FileServer(http.Dir("html"))
http.Handle("/", html)
// 这个总是返回404错误
data := http.FileServer(http.Dir("data"))
http.Handle("/data/", data)
fmt.Println("Listening on port " + port + "...")
log.Fatal(http.ListenAndServe(port, nil))
}
非常感谢任何帮助!
英文:
Beginner Go Question
I have this directory structure.
app_executable
html
|
- index.html
data
|
- static_file.json
I can't get it to serve the static_file.json
in data/static_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))
}
Any help is appreciated!
答案1
得分: 2
问题在于FileServer处理程序实际上是在这个路径上查找文件:
./data/data/static_file.json
而不是
./data/statif_file.json
如果你创建第一个文件,你的代码将会工作。你可能想要做的是:
data := http.FileServer(http.Dir("data"))
http.Handle("/", data)
或者
data := http.FileServer(http.Dir("data"))
http.Handle("/data/", http.StripPrefix("/data/", data))
我会选择前者,因为这可能是你真正想要做的。将处理程序附加到根目录,任何与/data/<file_on_disk>匹配的内容都会按预期返回。
如果你查看实际调用的返回结果:
data := http.FileServer(http.Dir("data"))
你会看到它是
&http.fileHandler{root:"data"}
它表示根目录在./data下,所以尝试在该根目录下查找与请求路径匹配的文件。在你的情况下,该路径是data/static_file.json,所以最终它会检查./data/data/static_file.json,但该文件不存在,所以返回404错误。
英文:
The problem is that the FileServer handler is actually looking for a file on this path:
./data/data/static_file.json
instead of
./data/statif_file.json
If you make the first file exist, your code will work. What you probably want to do is either:
data := http.FileServer(http.Dir("data"))
http.Handle("/", data)
Or
data := http.FileServer(http.Dir("data"))
http.Handle("/data/", http.StripPrefix("/data/", data))
I would opt for the former, as it is probably what you really want to do. Attach the handler to the root, and anything matching /data/<file_on_disk> will return as expected.
If you look at what is actually returned from the call to
data := http.FileServer(http.Dir("data"))
You will see it is
&http.fileHandler{root:"data"}
Which is saying the root is at ./data, so try finding a file under that root matching the path of the request. In your case that path is data/static_file.json so ultimately it checks for ./data/data/static_file.json which does not exist and it 404s
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论