If I use http.Redirect in a middleware, do I explicitly have to return after the http.Redirect before calling next.ServeHTTP(w, r)?
If I have something like this, do I have to return explicitly after every http.Redirect in order for the code to stop executing after the redirect? What happens if I don't return?
// HTTPSNonWWWRedirect redirects http requests to https non www.
func HTTPSNonWWWRedirect(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.TLS == nil {
u := *r.URL
u.Scheme = "https"
if r.Host[:3] == "www" {
u.Host = r.Host[4:]
http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
return
}
http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
return
}
next.ServeHTTP(w, r)
})
}
http.Redirect
just redirects the user to a different route. It does not break out from the code execution.
You could also use else
statement to wrap around the last next.ServeHTTP(w, r)
which makes it looks cleaner. But Go's idiom tends to use return
instead of else
.