Last active
July 10, 2020 03:48
-
-
Save liujianping/088c764eb3609a4410d19a1045d89e8f to your computer and use it in GitHub Desktop.
证书自动化 golang autocert sample
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" | |
"io" | |
"log" | |
"net/http" | |
"syscall" | |
"github.com/x-mod/httpserver" | |
"github.com/x-mod/routine" | |
"github.com/x-mod/tlsconfig" | |
"golang.org/x/crypto/acme/autocert" | |
) | |
func main() { | |
certs := &autocert.Manager{ | |
Prompt: autocert.AcceptTOS, | |
HostPolicy: autocert.HostWhitelist("your-domain"), | |
Cache: autocert.DirCache("your-local-certs-cache-dir"), | |
Email: "your-email-address", | |
} | |
srv := httpserver.New( | |
httpserver.Address(":80"), | |
httpserver.HTTPHandler(certs.HTTPHandler(nil)), | |
) | |
srvs := httpserver.New( | |
httpserver.Address(":443"), | |
httpserver.TLSConfig(tlsconfig.New( | |
tlsconfig.GetCertificate(certs.GetCertificate), | |
)), | |
httpserver.HTTPHandler( | |
http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { | |
io.WriteString(w, "Hello, world!\n") | |
}), | |
), | |
) | |
if err := routine.Main( | |
context.TODO(), | |
routine.ExecutorFunc(srvs.Serve), | |
routine.Go(routine.ExecutorFunc(srv.Serve)), | |
routine.Signal(syscall.SIGINT, routine.SigHandler(func() { | |
srv.Close() | |
srvs.Close() | |
}))); err != nil { | |
log.Println(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment