Created
February 3, 2018 13:07
-
-
Save davidbanham/ffdd550b0476dbd062aede64e6418899 to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"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