首頁  >  文章  >  後端開發  >  在 Golang 中使用 Gorilla Mux 提供 JavaScript 和資產檔案時遇到問題

在 Golang 中使用 Gorilla Mux 提供 JavaScript 和資產檔案時遇到問題

王林
王林轉載
2024-02-09 16:12:09872瀏覽

在 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刪除