Remove trailing slash from urls - Go static server

3.3k Views Asked by At

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.

1

There are 1 best solutions below

0
On

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 page

like 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