Reputation: 183
I've set up a simple Go static file server with http.FileServer
. If I have a directory structure like public > about > index.html
, the server will correctly resolve /about
to about > index.html
, but it adds a trailing slash so the url becomes /about/
.
Is there a simple way to remove these trailing slashes when using http.FileServer
? Ultimately, it works either way - it's mostly just a personal preference to not have the trailing slashes if possible.
Upvotes: 1
Views: 4184
Reputation: 22037
When you register the route /about/
an implicit route of /about
is added (which redirects clients to /about/
).
To work around this, you can register two explicit routes:
/about
to serve your index.html
/about/
to serve the http.FileServer
to handle any HTML assets for the pagelike so:
// what you had before
h.Handle("/about/",
http.StripPrefix(
"/about/",
http.FileServer(http.Dir("/tmp/about-files")),
),
)
// prevents implicit redirect to `/about/`
h.HandleFunc("/about",
func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html") // serves a single file from this route
},
)
https://play.golang.org/p/WLwLPV5WuJm
Upvotes: 2