Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I rewrite / redirect from http to https in Go?

Tags:

go

I have put up TLS and it works. I know how to rewrite from http to https in nginx, but I do not use nginx anymore. I don't know how to do this in Go properly.

func main() {

    certificate := "/srv/ssl/ssl-bundle.crt"
    privateKey := "/srv/ssl/mykey.key"

    http.HandleFunc("/", rootHander)
    // log.Fatal(http.ListenAndServe(":80", nil))
    log.Fatal(http.ListenAndServeTLS(":443", certificate, privateKey, nil))
}

func rootHander(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("To the moon!"))
}

How would I do this in a good way?

like image 597
Alex Avatar asked May 31 '16 02:05

Alex


People also ask

What does it mean to redirect HTTP to HTTPS?

Although HTTP and HTTPs seem similar enough, it's important to know the difference between the two. Here's how it all boils down: HTTPS is secure, while HTTP is not. The websites that have made the move to redirect HTTP to HTTPS appear with a padlock on the browser bar before the URL.


1 Answers

Create a handler which handles redirection to https like:

func redirectTLS(w http.ResponseWriter, r *http.Request) {
    http.Redirect(w, r, "https://IPAddr:443"+r.RequestURI, http.StatusMovedPermanently)
}

Then redirect http traffic:

go func() {
    if err := http.ListenAndServe(":80", http.HandlerFunc(redirectTLS)); err != nil {
        log.Fatalf("ListenAndServe error: %v", err)
    }
}()
like image 115
khrm Avatar answered Sep 30 '22 13:09

khrm