
在 Golang 中使用 Gorilla Mux 提供 JavaScript 和资产文件时遇到问题,这是许多开发人员在使用该库时可能经常遇到的情况。Gorilla Mux 是一个流行的路由库,但在处理静态资源时可能会遇到一些困难。php小编小新将在本文中为您介绍一些常见的问题以及解决方案,以帮助您更好地使用 Gorilla Mux 在 Golang 项目中提供 JavaScript 和资产文件。
我有这样的文件系统:
-- api
-> api.go
-- styles
-> style1.css
-> style2.css
-> ...
-- scripts
-> script1.js
-> script2.js
-> ...
-- static
-> page1.html
-> page2.html
-> ...
-- assets
-> image1.png
-> image2.png
-> ...
-- main.go在 api.go 文件中,我像这样设置我的 Gorilla mux 服务器,(从这个 Golang Gorilla mux 获取代码,http.FileServer 返回 404):
func (api *APIServer) Run() {
router := mux.NewRouter()
router.PathPrefix("/styles/").Handler(http.StripPrefix("/styles/",
http.FileServer(http.Dir("styles"))))
router.PathPrefix("/").Handler(http.StripPrefix("/",
http.FileServer(http.Dir("static"))))
router.PathPrefix("/scripts/").Handler(http.StripPrefix("/scripts/",
http.FileServer(http.Dir("scripts"))))
router.PathPrefix("/assets/").Handler(http.StripPrefix("/assets/",
http.FileServer(http.Dir("assets"))))
if err := http.ListenAndServe(api.listenAddr, router); err != nil {
log.Printf("error starting server %s", err.Error())
}
fmt.Println("server start running")
}html 文件:
立即学习“Java免费学习笔记(深入)”;
<link rel="stylesheet" type="text/css" href="styles\login.css" />
<script src="scripts\login.js"></script>
<img
id="img-show"
src="assets\bin.png"
alt=""
width="25px"
/>浏览器只能看到 html(静态)和 css(样式),但看不到脚本和资源,尽管事实上一切都与前两者相同。错误:
(Golang Gorilla mux 与 http.FileServer 返回 404)这两个选项仅对 html 和 css 文件有帮助,更改路径也没有给出任何结果。
您的问题是由“/”处理程序引起的,它匹配“/assets”和“/scripts”,并在这些路由之前声明。请参阅此处 gorilla/mux 如何匹配路由
如果重新排列路线顺序,这个问题就会消失:
router.PathPrefix("/styles/").Handler(http.StripPrefix("/styles/",
http.FileServer(http.Dir("styles"))))
router.PathPrefix("/scripts/").Handler(http.StripPrefix("/scripts/",
http.FileServer(http.Dir("scripts"))))
router.PathPrefix("/assets/").Handler(http.StripPrefix("/assets/",
http.FileServer(http.Dir("assets"))))
router.PathPrefix("/").Handler(http.StripPrefix("/",
http.FileServer(http.Dir("static"))))以上就是在 Golang 中使用 Gorilla Mux 提供 JavaScript 和资产文件时遇到问题的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号