gpt4 book ai didi

javascript - 无法使用 golang 服务器定位静态脚本

转载 作者:IT王子 更新时间:2023-10-29 01:45:38 25 4
gpt4 key购买 nike

我写了一个 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.go

func 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"

这是怎么回事?

编辑-

我已经简化了一切并尝试做到这一点

router.Handle("../static/scripts", http.StripPrefix("../static/scripts", http.FileServer(http.Dir("."))))

但这仍然不起作用。

最佳答案

尝试以下操作:

// 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"

关于javascript - 无法使用 golang 服务器定位静态脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32444993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com