在辅助路由(“ / route / secondary / route”)Golang中提供静态文件

在辅助路由(“ / 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:

localhost:8080/static/file.example

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

localhost:8080/clients/static/file.example

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:

tree

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.