diff --git a/http.go b/http.go index 092db5299..32fd62362 100644 --- a/http.go +++ b/http.go @@ -21,17 +21,20 @@ type Server struct { Opts *Options } -func (s *Server) ListenAndServe() { +func (s *Server) ListenAndServe(ctx context.Context) { if s.Opts.HttpsAddress == "" && s.Opts.HttpAddress == "" { log.Fatalf("FATAL: must specify https-address or http-address") } if s.Opts.HttpsAddress != "" { - go s.ServeHTTPS() + go s.ServeHTTPS(ctx) } if s.Opts.HttpAddress != "" { go s.ServeHTTP() } - select {} + + select { + case <-ctx.Done(): + } } func (s *Server) ServeHTTP() { @@ -69,7 +72,7 @@ func (s *Server) ServeHTTP() { log.Printf("HTTP: closing %s", listener.Addr()) } -func (s *Server) ServeHTTPS() { +func (s *Server) ServeHTTPS(ctx context.Context) { addr := s.Opts.HttpsAddress config := oscrypto.SecureTLSConfig(&tls.Config{}) @@ -82,7 +85,7 @@ func (s *Server) ServeHTTPS() { if err != nil { log.Fatalf("FATAL: loading tls config (%s, %s) failed - %s", s.Opts.TLSCertFile, s.Opts.TLSKeyFile, err) } - go servingCertProvider.Run(context.Background(), 1) + go servingCertProvider.Run(ctx, 1) config.GetCertificate = func(_ *tls.ClientHelloInfo) (*tls.Certificate, error) { // this disregards information from ClientHello but we're not doing SNI anyway diff --git a/main.go b/main.go index e72a57887..24cbbf6c5 100644 --- a/main.go +++ b/main.go @@ -1,14 +1,17 @@ package main import ( + "context" "flag" "fmt" "log" "net/http" _ "net/http/pprof" "os" + "os/signal" "runtime" "strings" + "syscall" "time" "github.com/BurntSushi/toml" @@ -169,6 +172,16 @@ func main() { }() } + ctx, cancel := context.WithCancel(context.Background()) + + term := make(chan os.Signal, 1) + signal.Notify(term, os.Interrupt, syscall.SIGTERM) + go func() { + <-term + log.Print("received SIGTERM, exiting gracefully...") + cancel() + }() + var h http.Handler = oauthproxy if opts.RequestLogging { h = LoggingHandler(os.Stdout, h, true) @@ -177,5 +190,5 @@ func main() { Handler: h, Opts: opts, } - s.ListenAndServe() + s.ListenAndServe(ctx) }