首頁 > 後端開發 > Golang > 主體

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

王林
發布: 2024-02-09 16:12:09
轉載
894 人瀏覽過

在 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
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!