how to redirect http to https in Gorilla Mux?
Start another HTTP handler on the other port in a separate go routine
go http.ListenAndServe(":80", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://"+r.Host+r.URL.String(), http.StatusMovedPermanently)
}))
What I ended up doing was that, I wrote a middleware that redirects HTTP requests to HTTPS
func RedirectToHTTPSRouter(next http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
proto := req.Header.Get("x-forwarded-proto")
if proto == "http" || proto == "HTTP" {
http.Redirect(res, req, fmt.Sprintf("https://%s%s", req.Host, req.URL), http.StatusPermanentRedirect)
return
}
next.ServeHTTP(res, req)
})
}
func main() {
router := mux.NewRouter()
httpsRouter := RedirectToHTTPSRouter(router)
log.Fatal(http.ListenAndServe(lib.Settings.Address, httpsRouter))
}