首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Fileserver()总是返回index.html

Fileserver()总是返回index.html
EN

Stack Overflow用户
提问于 2017-02-16 02:34:28
回答 1查看 158关注 0票数 1

我的项目结构如下:

代码语言:javascript
复制
/rootfolder
    index.html
    main.js
    main.go

我试图通过FileServer()提供静态javascript文件,它总是将index.html作为响应而不是main.js返回

在main.go中:

代码语言:javascript
复制
serveFile := http.StripPrefix("/res/", http.FileServer(http.Dir(".")))
http.HandleFunc("/", indexHandler)
http.Handle("/res", serveFile)
http.ListenAndServe(":8080", nil)

在index.html main.js中引用如下:

代码语言:javascript
复制
<script src="/res/main.js"></script>

从浏览器中的“网络”选项卡中可以看出,FileServer()总是将index.html文件作为对/res/main.js的响应返回

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-16 02:42:01

使用尾随斜杠注册文件处理程序,以指示要匹配子树。有关使用尾斜杠的更多信息,请参见文档

代码语言:javascript
复制
http.Handle("/res/", serveFile)

另外,使用句柄而不是HandleFunc。

提供索引文件是因为"/“匹配其他路径不匹配的所有路径。若要在这些情况下返回404,请将索引处理程序更新为:

代码语言:javascript
复制
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.
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42263791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档