I’m trying to redirect from HTTP to HTTPS in Go, but no matter what it goes to localhost:
I define the servers and run them:
httpServer = &http.Server{
Addr: login.HttpPORT,
Handler: http.HandlerFunc(redirectNonSecure),
}
httpsServer = &http.Server{
Addr: login.HttpsPORT,
TLSConfig: &tlsConf,
}
errChan := make(chan error, 2)
go func() {
log.Println("Starting HTTP server on :8081")
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
errChan <- err
}
}()
go func() {
log.Println("Starting HTTPS server on :8082")
if err := httpsServer.ListenAndServeTLS(certPath, keyPath); err != nil && err != http.ErrServerClosed {
errChan <- err
}
}()
log.Fatalf("Server error: %v", <-errChan)
And here is the redirect func:
func redirectNonSecure(w http.ResponseWriter, r *http.Request) {
redirectURL := "https://" + r.Host + httpsServer.Addr + r.RequestURI
http.Redirect(w, r, redirectURL, http.StatusMovedPermanently)
}
It always redirects to https://127.0.0.1:8082
and it should return https://ipAddr:8082
If i run it from localhost there’s no issue, obviously, if i go directly to the https without redirect it also worls fine, this is just when redirecting.
I also tried hardcoding the IP inside the redirect function but it still redirects to localhost which makes me think there’s something else at play here.