Go Gorrilla Mux will keep redirecting with 301 while using StrictSlash(true), how to return the json

Viewed 1507

This is part of my main function that I use for my end points

r := mux.NewRouter()
r.StrictSlash(true)
r.HandleFunc("/", test)
r.HandleFunc("/feature/list/", a.FeatureListHandler)
log.Fatal(http.ListenAndServe(":8080", r))

but when I curl localhost:8080/feature/list I get

<a hef="/feature/list">Moved Permanently</a>

However, when I curl localhost:8080/feature/list/ I get my json.

How do I make it so that both routes will return the json I want.

2 Answers

I use the following middleware to deal with this

func suffixMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // remove the trailing slash from our URL Path if it's not root
        if r.URL.Path != "/" {
            r.URL.Path = strings.TrimSuffix(r.URL.Path, "/")
        }

        // Call the next handler, which can be another middleware in the chain, or the final handler.
        next.ServeHTTP(w, r)
    })
}

Then you pass your router through such as: (suffixMiddleware(router))

Related