Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go http.FileServer始终为404';当文件存在时,单击“s”_Go - Fatal编程技术网

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"}