Golang: redirect http to https
July 26, 2015
Google (and others) are heavily pushing mass adoption of https for serving all online content. So, if you weren’t worried about it already, hopefully you are now :) Here is how you can setup your golang program so it directs all http traffic to https:
1 package main
2
3 import (
4 "io"
5 "net/http"
6 )
7
8 //hello world function
9 func hello(w http.ResponseWriter, r *http.Request) {
10 io.WriteString(w, "Hello world!")
11 }
12
13 func main() {
14 //pull environment variables
15 portHTTPS := os.Getenv("MYAPP_PORT_HTTPS")
16 portHTTP := os.Getenv("MYAPP_PORT_HTTP")
17 publicKeyPath := os.Getenv("MYAPP_PUBLICKEY_PATH")
18 privateKeyPath := os.Getenv("MYAPP_PRIVATEKEY_PATH")
19
20 //add paths
21 mux := http.NewServeMux()
22 mux.HandleFunc("/", hello)
23
24 //serve https in goroutine
25 go func() {
26 http.ListenAndServeTLS(":"+portHTTPS, publicKeyPath, privateKeyPath, nil)
27 }()
28
29 //redirect http to https
30 http.ListenAndServe(":"+portHTTP, http.HandlerFunc(redirectHTTP))
31 }