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

58wvjzkj  于 5个月前  发布在  Go
关注(0)|答案(1)|浏览(58)

我的文件系统是这样的:

-- 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 with http.FileServer returning 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(样式),但看不到脚本和资源,尽管所有操作都与前两者相同。错误:
100d1x

的字符串
Golang Gorilla mux with http.FileServer returning 404)这两个选项都只对html和css文件有帮助,更改路径也没有给予任何结果。

iqih9akk

iqih9akk1#

您的问题是由“/”处理程序引起的,它匹配“/assets”和“/scripts”,并且在这些路由之前声明。
如果你重新排列路线顺序,这个问题就不会出现了:

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

字符串

相关问题