Skip to content

Instantly share code, notes, and snippets.

@liujianping
Last active July 10, 2020 03:48
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 liujianping/088c764eb3609a4410d19a1045d89e8f to your computer and use it in GitHub Desktop.
Save liujianping/088c764eb3609a4410d19a1045d89e8f to your computer and use it in GitHub Desktop.
证书自动化 golang autocert sample
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