jas*_*son 55 web-applications go mux
我试图使用Gorilla工具包的mux包来路由Go Web服务器中的URL.利用这个问题为导向,我有以下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)
}
Run Code Online (Sandbox Code Playgroud)
目录结构是:
...
main.go
static\
| index.html
| js\
| <js files>
| css\
| <css files>
Run Code Online (Sandbox Code Playgroud)
Javascript和CSS文件的引用方式index.html如下:
...
<link rel="stylesheet" href="css/redmond/jquery-ui.min.css"/>
<script src="js/jquery.min.js"></script>
...
Run Code Online (Sandbox Code Playgroud)
当我http://localhost:8100在我的Web浏览器中访问index.html内容成功传递时,所有js和cssURL都返回404.
如何让程序从static子目录中提供文件?
Chr*_*loe 80
我想你可能在寻找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)
}
Run Code Online (Sandbox Code Playgroud)
cod*_*eak 40
经过大量的反复试验,上述两个答案都帮助我找到了对我有用的东西.我在web应用程序的根目录中有静态文件夹.
随着PathPrefix我必须使用StripPrefix递归途径上班.
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
s := http.StripPrefix("/static/", http.FileServer(http.Dir("./static/")))
r.PathPrefix("/static/").Handler(s)
http.Handle("/", r)
err := http.ListenAndServe(":8081", nil)
}
Run Code Online (Sandbox Code Playgroud)
我希望它可以帮助别人遇到问题.
我在这里有这个代码非常好用并且可以重复使用.
func ServeStatic(router *mux.Router, staticDirectory string) {
staticPaths := map[string]string{
"styles": staticDirectory + "/styles/",
"bower_components": staticDirectory + "/bower_components/",
"images": staticDirectory + "/images/",
"scripts": staticDirectory + "/scripts/",
}
for pathName, pathValue := range staticPaths {
pathPrefix := "/" + pathName + "/"
router.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix,
http.FileServer(http.Dir(pathValue))))
}
}
router := mux.NewRouter()
ServeStatic(router, "/static/")
Run Code Online (Sandbox Code Playgroud)
尝试这个:
fileHandler := http.StripPrefix("/static/", http.FileServer(http.Dir("/absolute/path/static")))
http.Handle("/static/", fileHandler)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31509 次 |
| 最近记录: |