Trailing slash in URL does not load css/js etc

I have problem with url path not loading the assets when adding a trailing slash.

https://static.go4webdev.org/why (works as expected)
The path for a svg will be /icn/meatballs.svg
https://static.go4webdev.org/why/ (does not load css/js etc)
The path for a svg will be why/icn/meatballs.svg

It sort of ruin the path to some assets in the public folder.

func init() {
	tpl = template.Must(template.ParseGlob("public/tmpl/*.html"))
	http.Handle("/img/", http.StripPrefix("/img/", http.FileServer(http.Dir("./public/img"))))
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./public/css"))))
	http.Handle("/icn/", http.StripPrefix("/icn/", http.FileServer(http.Dir("./public/icn"))))
	http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("./public/js"))))
	http.Handle("/mov/", http.StripPrefix("/mov/", http.FileServer(http.Dir("./public/mov"))))
	http.Handle("/misc/", http.StripPrefix("/misc/", http.FileServer(http.Dir("./public/misc"))))
}

Any idea what to do to load the page correct?

This is how relative pathes in HTML work (and yoour browser is to blame not Go). The following possible solutions exist (the order is just random as they got into my mind and does not reflect any preference):

  1. Use absolute rather than relative for assets
  2. always redirect from trailing slash to no trailing slash and write asset references accordingly
  3. always redirect from no trailing slash to trailing slash and write asset references accordingly
  4. set a <base> and write asset references accordingly
1 Like