// wait group to ensure a clean exit
wg sync.WaitGroup
log.Println("start listener")
// wrap entire mux with logging, bearer token, and apiKey middleware
wrappedMux := NewEnsureAuth(mux)
// run via a goroutine
wg.Add(1)
go func() {
defer wg.Done()
// create a 'server' so we can later use 'shutdown'
srv := &http.Server{
Addr: ":8080",
Handler: wrappedMux,
}
// handle SIGINT / SIGTERM
go func() {
sigint := make(chan os.Signal)
signal.Notify(sigint, os.Interrupt, syscall.SIGTERM)
<-sigint
log.Println("catch SIGTERM")
// cancel routine during shutdown, if needed
sigctx, sigcancel := context.WithTimeout(context.Background(), 20*time.Second)
defer func() {
// extra handling here
sigcancel()
}()
// stop listening, finish calls in progress, then exit
if err := srv.Shutdown(sigctx); err != nil {
log.Fatalf("- shutdown handler: %+v", err)
}
log.Print("- shutdown handler exited")
}()
// begin handling connections
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
wg.Wait()
go http.Server example: clean exit with pod delete
Posted in Development, Kubernetes.