Skip to content

Commit

Permalink
chore: support context with graceful shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
appleboy committed Aug 30, 2022
1 parent 5f664b2 commit c96a2dd
Showing 1 changed file with 40 additions and 4 deletions.
44 changes: 40 additions & 4 deletions autotls.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package autotls

import (
"context"
"crypto/tls"
"log"
"net/http"
Expand All @@ -9,18 +10,53 @@ import (
"golang.org/x/sync/errgroup"
)

// Run support 1-line LetsEncrypt HTTPS servers
func Run(r http.Handler, domain ...string) error {
func run(ctx context.Context, r http.Handler, domain ...string) error {
var g errgroup.Group

s1 := &http.Server{
Addr: ":http",
Handler: http.HandlerFunc(redirect),
}
s2 := &http.Server{
Handler: r,
}

g.Go(func() error {
return s1.ListenAndServe()
})
g.Go(func() error {
return http.ListenAndServe(":http", http.HandlerFunc(redirect))
return s2.Serve(autocert.NewListener(domain...))
})

g.Go(func() error {
return http.Serve(autocert.NewListener(domain...), r)
if ctx == nil {
return nil
}
<-ctx.Done()

var gShutdown errgroup.Group
gShutdown.Go(func() error {
return s1.Shutdown(context.Background())
})
gShutdown.Go(func() error {
return s2.Shutdown(context.Background())
})

return gShutdown.Wait()
})
return g.Wait()
}

// Run support 1-line LetsEncrypt HTTPS servers with graceful shutdown
func RunWithContext(ctx context.Context, r http.Handler, domain ...string) error {
return run(ctx, r, domain...)
}

// Run support 1-line LetsEncrypt HTTPS servers
func Run(r http.Handler, domain ...string) error {
return run(nil, r, domain...)
}

// RunWithManager support custom autocert manager
func RunWithManager(r http.Handler, m *autocert.Manager) error {
return RunWithManagerAndTLSConfig(r, m, *m.TLSConfig())
Expand Down

0 comments on commit c96a2dd

Please sign in to comment.