gogorillanegroni

Serving Subdirectories in HTTP handlers [GoLang]


I have the following code:

r := mux.NewRouter()
r.Handle("/", http.FileServer(http.Dir("./frontend/build/")))
r.Handle("/static", http.FileServer(http.Dir("./frontend/build/static/")))
r.PathPrefix("/api").Handler(auth)

/api is supposed to be secure. If a user hits /, I want them to view the index.html in the PROJECTDIR/frontend directory.

The frontend directory looks like

frontend
    /build
        index.html
        /static
            /js
            /css
            /media

The index.html loads all contents from /static. No matter how I seem to configure this, when I visit localhost:3000, I can get the index.html but everything under /static is 404'd.

How am I configuring this incorrectly?


Solution

  • Assuming you want to serve the whole content of the directory "static" on the endpoint /static and you are running a bsd/linux machine the following syntax should work:

    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))