Redirecting from HTTP to HTTPS in Go
In order to enforce HTTPS-only connections, you can redirect HTTP requests to HTTPS counterparts. Here's how to do it effectively in Go:
1. Create a Redirect Handler:
Define a custom HTTP handler that handles the redirection:
func redirectToTls(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "https://IPAddr:443"+r.RequestURI, http.StatusMovedPermanently) }
This handler will redirect all HTTP requests to the corresponding HTTPS URL (replace "IPAddr" with your server's IP address or domain name).
2. Redirect HTTP Traffic:
Start an HTTP server that listens on port 80 and uses the redirect handler:
go func() { if err := http.ListenAndServe(":80", http.HandlerFunc(redirectToTls)); err != nil { log.Fatalf("ListenAndServe error: %v", err) } }()
With this setup, all HTTP requests received on port 80 will be automatically redirected to their HTTPS counterparts, ensuring a secure connection to your website.
The above is the detailed content of How to Redirect HTTP to HTTPS in Go?. For more information, please follow other related articles on the PHP Chinese website!