How to Redirect HTTP Traffic to HTTPS in Go
Problem:
You've enabled TLS, allowing your Go application to accept HTTPS connections. However, you also want to redirect HTTP traffic to HTTPS.
Solution:
Create a custom handler to handle HTTP traffic and redirect it to HTTPS:
import ( "net/http" ) func redirectToTls(w http.ResponseWriter, r *http.Request) { // If you are serving on Go servers, you can use "r.Host" http.Redirect(w, r, "https://your-domain-name.com"+r.RequestURI, http.StatusMovedPermanently) }
Next, add the following code to redirect HTTP traffic:
go func() { if err := http.ListenAndServe(":80", http.HandlerFunc(redirectToTls)); err != nil { log.Fatalf("ListenAndServe error: %v", err) } }()
This will start a separate goroutine for handling HTTP traffic, where it redirects incoming HTTP requests to their HTTPS counterparts.
The above is the detailed content of How to Redirect HTTP to HTTPS in a Go Application?. For more information, please follow other related articles on the PHP Chinese website!