2017-02-16 68 views
1

我的项目结构如下:文件服务器()总是返回的index.html

/rootfolder 
    index.html 
    main.js 
    main.go 

我试图通过文件服务器(),它总是返回index.html作为响应提供静态的JavaScript文件而不是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> 

从我的浏览器的网络选项卡,看来文件服务器()总是返回index.html文件为/res/main.js

回答

2

一个响应寄存器以斜线的文件处理程序,指示要匹配子树。有关使用尾部斜线的更多信息,请参见documentation

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 
    } 
    ... whatever code you had here before. 
} 
相关问题