gogorillafileserver

Trouble serving JavaScript and asset files with Gorilla Mux in Golang


I have file system like this:

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

In api.go file I set my Gorilla mux server like this, (got code from this 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 file:

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

The browser sees only html (static) and css (styles), but does not see scripts and assets, despite the fact that everything is done identically to the first two. Error:

console error enter image description here

(Golang Gorilla mux with http.FileServer returning 404) Both options only helped for html and css files, changing the paths also didn't give any results.


Solution

  • Your problem is caused by the "/" handler, which matches "/assets" and "/scripts", and is declared before those routes. See here how gorilla/mux matches routes

    If you rearrange the routes order, this problem will be gone:

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