Skip to content

Instantly share code, notes, and snippets.

@trigun117
Last active March 27, 2019 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trigun117/646dd726a690da409421d9a50c37e617 to your computer and use it in GitHub Desktop.
Save trigun117/646dd726a690da409421d9a50c37e617 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/tls"
"fmt"
"golang.org/x/crypto/acme/autocert"
"log"
"net/http"
"os"
)
func main() {
// setup a simple handler which sends a HTHS header for six months (!)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Strict-Transport-Security", "max-age=15768000 ; includeSubDomains")
fmt.Fprintf(w, "Hello, HTTPS world!")
})
// create the autocert.Manager with domains and path to the cache
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(os.Getenv("DOMAIN")),
Cache: autocert.DirCache("."),
}
// create the server itself
server := &http.Server{
Addr: ":https",
TLSConfig: &tls.Config{
GetCertificate: certManager.GetCertificate,
},
}
log.Printf("Serving http/https for domains: %+v", os.Getenv("DOMAIN"))
go func() {
// serve HTTP, which will redirect automatically to HTTPS
h := certManager.HTTPHandler(nil)
log.Fatal(http.ListenAndServe(":http", h))
}()
// serve HTTPS!
log.Fatal(server.ListenAndServeTLS("", ""))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment