Fileserver() 总是返回 index.html

huangapple go评论79阅读模式
英文:

Fileserver() always returns index.html

问题

我的项目结构如下:

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

英文:

My project structure is as follows:

/rootfolder
    index.html
    main.js
    main.go

I'm trying to serve the static javascript file through FileServer(), which always returns the index.html as a response instead of the main.js

In main.go:

serveFile := http.StripPrefix(&quot;/res/&quot;, http.FileServer(http.Dir(&quot;.&quot;)))
http.HandleFunc(&quot;/&quot;, indexHandler)
http.Handle(&quot;/res&quot;, serveFile)
http.ListenAndServe(&quot;:8080&quot;, nil)

Inside index.html main.js is referenced as follows:

&lt;script src=&quot;/res/main.js&quot;&gt;&lt;/script&gt;

From the network tab in my browser, it appears that FileServer() is always returning the index.html file as a response to /res/main.js

答案1

得分: 2

将文件处理程序注册为带有斜杠的路径,以指示您希望匹配子树。有关斜杠的使用更多信息,请参阅文档

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
    }
    // ... 在此之前的任何代码。
}
英文:

Register the file handler with a trailing slash to indicate that you want to match the subtree. See the documentation for more info on the use of the trailing slash.

http.Handle(&quot;/res/&quot;, serveFile)

Also, use Handle instead of HandleFunc.

The index file was served because "/" matches all paths not matched by some other path. To return 404 in these cases, update the index handler to:

func indexHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != &quot;/&quot; {
	  http.Error(w, &quot;Not found&quot;, 404)
	  return
    }
    ... whatever code you had here before.
}

huangapple
  • 本文由 发表于 2017年2月16日 10:34:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/42263791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定