From 5badb851e43d3afc94bfd6c68502fcb0e5b37615 Mon Sep 17 00:00:00 2001 From: appleboy Date: Sun, 12 May 2024 12:27:32 +0800 Subject: [PATCH] refactor: refactor and enhance autocert TLS handling - Move import of `golang.org/x/crypto/acme/autocert` in `autocertcache.go` - Update permission format in `os.MkdirAll` call to octal in `autocertcache.go` - Add `time` package and `ReadHeaderTimeout` variable in `autotls.go` - Set `ReadHeaderTimeout` for HTTP server configurations in `autotls.go` - Refactor HTTP server creation to use a structured approach in `autotls.go` Signed-off-by: appleboy --- autocertcache.go | 5 +++-- autotls.go | 28 +++++++++++++++++++--------- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/autocertcache.go b/autocertcache.go index 4cc60ca..ba56f50 100644 --- a/autocertcache.go +++ b/autocertcache.go @@ -2,15 +2,16 @@ package autotls import ( "errors" - "golang.org/x/crypto/acme/autocert" "os" "path/filepath" "runtime" + + "golang.org/x/crypto/acme/autocert" ) func getCacheDir() (autocert.DirCache, error) { dir := cacheDir() - if err := os.MkdirAll(dir, 0700); err != nil { + if err := os.MkdirAll(dir, 0o700); err != nil { return "", errors.New("warning: autocert.NewListener not using a cache: " + err.Error()) } return autocert.DirCache(dir), nil diff --git a/autotls.go b/autotls.go index a378910..668ea24 100644 --- a/autotls.go +++ b/autotls.go @@ -5,6 +5,7 @@ import ( "crypto/tls" "log" "net/http" + "time" "golang.org/x/crypto/acme/autocert" "golang.org/x/sync/errgroup" @@ -13,19 +14,22 @@ import ( type tlsContextKey string var ( - ctxKey = tlsContextKey("autls") - todoCtx = context.WithValue(context.Background(), ctxKey, "done") + ctxKey = tlsContextKey("autls") + todoCtx = context.WithValue(context.Background(), ctxKey, "done") + ReadHeaderTimeout = 3 * time.Second ) func run(ctx context.Context, r http.Handler, domain ...string) error { var g errgroup.Group s1 := &http.Server{ - Addr: ":http", - Handler: http.HandlerFunc(redirect), + Addr: ":http", + Handler: http.HandlerFunc(redirect), + ReadHeaderTimeout: ReadHeaderTimeout, } s2 := &http.Server{ - Handler: r, + Handler: r, + ReadHeaderTimeout: ReadHeaderTimeout, } g.Go(func() error { @@ -84,12 +88,18 @@ func RunWithManagerAndTLSConfig(r http.Handler, m *autocert.Manager, tlsc *tls.C tlsc.GetCertificate = defaultTLSConfig.GetCertificate tlsc.NextProtos = defaultTLSConfig.NextProtos s := &http.Server{ - Addr: ":https", - TLSConfig: tlsc, - Handler: r, + Addr: ":https", + TLSConfig: tlsc, + Handler: r, + ReadHeaderTimeout: ReadHeaderTimeout, } g.Go(func() error { - return http.ListenAndServe(":http", m.HTTPHandler(http.HandlerFunc(redirect))) + s := &http.Server{ + Addr: ":http", + Handler: m.HTTPHandler(http.HandlerFunc(redirect)), + ReadHeaderTimeout: ReadHeaderTimeout, + } + return s.ListenAndServe() }) g.Go(func() error { return s.ListenAndServeTLS("", "")