Serving static files in secondary routes ("/route/secondary/route") Golang

In my root handle ("/") or clients handle ("/clients") the static files are correctly avaliable, and looking the network tab on chrome, i see the server request like this:


But if i'm on the secondary handle ("/Clients/route"), don't work correctly, i see this:


The StripPrefix don't remove the "client" from the request.

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

http.HandleFunc("/", index)
http.HandleFunc("/clients", controllers.MostrarClientes)
http.HandleFunc("/clientes/route", controllers.MainIndex)

http.ListenAndServe(":8080", nil)


<link rel="stylesheet" href="static/leaflet/leaflet.css" />


File tree:


1 answer

  • answered 2018-02-13 02:37 James

    This isn't an issue with the handler, it is an issue with your HTML link.

    <link rel="stylesheet" href="static/leaflet/leaflet.css" /> is relative to the current URL.

    That is to say, static/leaflet/leaflet.css will be appended to the current URL - when you are on your homepage this isn't an issue as it translates to /static/leaflet/leaflet.css but when you are on your clients page it turns into /clients/static/leaflet/leaflet.css.

    The simple fix is just to add a leading / to your href:

    <link rel="stylesheet" href="/static/leaflet/leaflet.css" />

    This makes the URL absolute and it will be unaffected by visiting other pages of your website.