Skip to content

Instantly share code, notes, and snippets.

@snadrus
Created October 13, 2020 04:29
Show Gist options
  • Save snadrus/1ad2bff976650a39e953c6d0afa070ae to your computer and use it in GitHub Desktop.
Save snadrus/1ad2bff976650a39e953c6d0afa070ae to your computer and use it in GitHub Desktop.
// StartServer serves Handler over HTTPS(443) with a redirect on 80
// using an ACME certificate it creates & is cached in ./certs/
// and has sensible timeouts to avoid nasty clients.
// Note the timeouts don't work for slow transfers,
// but oddly are ok for websockets.
func StartServer(engine http.Handler, ...hostname string)
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(hostname...),
Cache: autocert.DirCache("certs"),
}
s := &http.Server{
Addr: ":https",
Handler: engine,
TLSConfig: certManager.TLSConfig(),
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
ReadHeaderTimeout: 2 * time.Second,
}
go http.ListenAndServe(":80", certManager.HTTPHandler(nil))
log.Fatal(s.ListenAndServeTLS("", ""))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment