首页  >  文章  >  后端开发  >  在 Golang 中使用 Gorilla Mux 提供 JavaScript 和资产文件时遇到问题

在 Golang 中使用 Gorilla Mux 提供 JavaScript 和资产文件时遇到问题

王林
王林转载
2024-02-09 16:12:09874浏览

在 Golang 中使用 Gorilla Mux 提供 JavaScript 和资产文件时遇到问题

在 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 文件:

<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中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除