Created
January 31, 2018 13:56
-
-
Save karl-gustav/4f6ca7972cbfd3b7ec0c53684a9d4429 to your computer and use it in GitHub Desktop.
Golang with letsencrypt https and http-->https redirect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/tls" | |
"net/http" | |
"golang.org/x/crypto/acme/autocert" | |
) | |
func main() { | |
certManager := autocert.Manager{ | |
Prompt: autocert.AcceptTOS, | |
HostPolicy: autocert.HostWhitelist("example.com"), //your domain here | |
Cache: autocert.DirCache("certs"), //folder for storing certificates | |
} | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("Hello world")) | |
}) | |
server := &http.Server{ | |
Addr: ":443", | |
TLSConfig: &tls.Config{ | |
GetCertificate: certManager.GetCertificate, | |
}, | |
} | |
go http.ListenAndServe(":80", http.HandlerFunc(redirectToHTTPS)) | |
server.ListenAndServeTLS("", "") //key and cert are comming from Let's Encrypt | |
} | |
func redirectToHTTPS(w http.ResponseWriter, req *http.Request) { | |
http.Redirect(w, req, "https://"+req.Host+req.URL.String(), http.StatusMovedPermanently) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment