Skip to content

Instantly share code, notes, and snippets.

@davidbanham
Created February 3, 2018 13:07
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 davidbanham/ffdd550b0476dbd062aede64e6418899 to your computer and use it in GitHub Desktop.
Save davidbanham/ffdd550b0476dbd062aede64e6418899 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"crypto/tls"
"fmt"
"log"
"net/http"
"os"
"strings"
"golang.org/x/crypto/acme/autocert"
)
func main() {
addr := ":" + os.Getenv("PORT")
router := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/health" {
w.Write([]byte("ok"))
} else {
// I pass this to a router from another package
// Do whatever you want
w.Write([]byte("Hello World"))
}
})
certMgr := autocert.Manager{
Prompt: func(_ string) bool {
return true
},
HostPolicy: func(_ context.Context, host string) error {
if strings.Contains(host, os.Getenv("DOMAIN")) {
return nil
} else {
return fmt.Errorf("Domain not valid")
}
},
}
s := &http.Server{
Handler: certMgr.HTTPHandler(router),
Addr: addr,
}
log.Printf("INFO Listening on: %s", addr)
go func() {
log.Fatal(s.ListenAndServe())
}()
s2 := &http.Server{
Handler: router,
Addr: ":https",
TLSConfig: &tls.Config{GetCertificate: certMgr.GetCertificate},
}
log.Printf("INFO Listening on 443 with TLS")
log.Fatal(s2.ListenAndServeTLS("", ""))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment