Skip to content

Instantly share code, notes, and snippets.

@karl-gustav
Created January 31, 2018 13:56
Show Gist options
  • Save karl-gustav/4f6ca7972cbfd3b7ec0c53684a9d4429 to your computer and use it in GitHub Desktop.
Save karl-gustav/4f6ca7972cbfd3b7ec0c53684a9d4429 to your computer and use it in GitHub Desktop.
Golang with letsencrypt https and http-->https redirect
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