我正在尝试使用 Gorilla 工具包的 mux
package在 Go Web 服务器中路由 URL。使用 this question作为指导,我有以下 Go 代码:
func main() {
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.Dir("./static/")))
r.HandleFunc("/search/{searchTerm}", Search)
r.HandleFunc("/load/{dataId}", Load)
http.Handle("/", r)
http.ListenAndServe(":8100", nil)
}
目录结构为:
...
main.go
static\
| index.html
| js\
| <js files>
| css\
| <css files>
Javascript 和 CSS 文件在 index.html
中引用如下:
...
<link rel="stylesheet" href="css/redmond/jquery-ui.min.css"/>
<script src="js/jquery.min.js"></script>
...
当我在网络浏览器中访问 http://localhost:8100
时,index.html
内容已成功交付,但是,所有 js
和 css
URL 返回 404。
如何让程序从 static
子目录中提供文件?
最佳答案
我想你可能正在寻找 PathPrefix
...
func main() {
r := mux.NewRouter()
r.HandleFunc("/search/{searchTerm}", Search)
r.HandleFunc("/load/{dataId}", Load)
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/")))
http.ListenAndServe(":8100", r)
}
关于web-applications - 使用 Gorilla 工具包通过根 URL 提供静态内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15834278/