Handling HTTP to HTTPS Redirection in Go
When deploying a TLS-enabled Go web application, redirecting HTTP traffic to HTTPS is crucial for security and maintaining a secure connection. Here's how to achieve this effectively:
Implement a custom HTTP handler responsible for handling the redirection. Define a function like the following:
func redirectToTls(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "https://IPAddr:443"+r.RequestURI, http.StatusMovedPermanently) }
In this handler, we create an HTTPS redirect to the same URI using the HTTP status code "Moved Permanently" (301).
Next, we need to handle HTTP traffic and redirect it to the HTTPS URL. Add the following code to your main Go file:
go func() { if err := http.ListenAndServe(":80", http.HandlerFunc(redirectToTls)); err != nil { log.Fatalf("ListenAndServe error: %v", err) } }()
This code creates a separate Go routine that listens on port 80 for HTTP traffic. When a request arrives, it redirects to the HTTPS URL using the redirectToTls handler.
This approach allows you to seamlessly redirect HTTP traffic to HTTPS and maintain a secure connection for your Go web application.
The above is the detailed content of How to Redirect HTTP to HTTPS in a Go Web Application?. For more information, please follow other related articles on the PHP Chinese website!