我写了一个 golang 网络服务器,我之前提供静态资源,但在改变我的项目结构后,这不再有效。这是我的项目结构ProjectFolder/ node_modules/ scripts/ test.es6.js server/ handlers.go main.go routes.go static/ scripts/ test.js test.js.map Gruntfile.js index.html package.json这是我的 index.html<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script><script type="text/javacript" src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script><script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script><script type="text/javascript" src="/static/scripts/test.js"</script><body> <div id="chart"></div></body>这是我的routes.gofunc NewRouter() *mux.Router { router := mux.NewRouter().StrictSlash(true) for _, route := range routes { router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(route.HandlerFunc) } for pathName, pathValue := range staticPaths { pathPrefix := "/" + pathName + "/" fmt.Println(pathPrefix) fmt.Println(pathValue) router.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix, http.FileServer(http.Dir(pathValue)))) } // router.PathPrefix("/static/scripts").Handler(http.FileServer(http.Dir("./static/scripts/"))) return router}var staticDirectory = "/static"var staticPaths = map[string]string{ "scripts": staticDirectory + "/scripts/",}var routes = Routes{ Route{ "Index", "GET", "/", Index, },}当我点击 localhost:8200 时,我在加载 test.js 时得到 404,但 index.html 正在被点击。以前,这是不使用 http.FileServer 来提供静态资源的问题,但我现在正在使用它。我已经尝试过 index.html 中路径的其他变体src= "static/scripts/test.js"src= "../static/scripts/test.js"到底是怎么回事?
1 回答
撒科打诨
TA贡献1934条经验 获得超2个赞
请尝试以下操作:
// Create new router.
gorillaMux := mux.NewRouter()
// Match /res/ prefix to local /res/ folder.
gorillaMux.PathPrefix("/res/").Handler(http.StripPrefix("/res/", http.FileServer(http.Dir("./res/"))))
这将使http://example.com/res/js/script.js寻找./res/js/script.js
因此,您必须在 HTML 中完全限定您的资源: src= "/static/scripts/test.js"
- 1 回答
- 0 关注
- 149 浏览
添加回答
举报
0/150
提交
取消