我正在尝试在 Go 中从 HTTP 重定向到 HTTPS,但无论它转到本地主机:
我定义服务器并运行它们:
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)
这是重定向功能:
func redirectNonSecure(w http.ResponseWriter, r *http.Request) {
redirectURL := "https://" + r.Host + httpsServer.Addr + r.RequestURI
http.Redirect(w, r, redirectURL, http.StatusMovedPermanently)
}
它总是重定向到
https://127.0.0.1:8082
并且应该返回 https://ipAddr:8082
如果我从本地主机运行它,显然没有问题,如果我直接进入 https 而不重定向它也很好,这只是在重定向时。
我还尝试在重定向函数中对 IP 进行硬编码,但它仍然重定向到本地主机,这让我觉得这里还有其他东西在起作用。
登录时使用端口。httpsPORT:
func redirectNonSecure(w http.ResponseWriter, r *http.Request) {
// Get host without port.
host, port, err := net.SplitHostPort(r.Host)
if err != nil {
// Use request host as is if request host does not
// include a port number or there is another error.
host = r.Host
}
// Add port to host if needed.
if login.HttpsPORT != ":433" {
host += login.HttpsPORT
}
redirectURL := "https://" + host + r.RequestURI
http.Redirect(w, r, redirectURL, http.StatusMovedPermanently)
}