Skip to content

Commit

Permalink
refactor(server): improve logging and handle shutdown signals with ea…
Browse files Browse the repository at this point in the history
…se (#39)

* fix(server): improve shutdown logging and handle force shutdown

* refactor(server): extract graceful shutdown logic into a separate function

- When received a signal early exit if there is no request
  • Loading branch information
mertssmnoglu authored Dec 29, 2024
1 parent 4e474b7 commit 2f8f3f9
Showing 1 changed file with 16 additions and 16 deletions.
32 changes: 16 additions & 16 deletions cmd/capture/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,29 +41,29 @@ func main() {
ReadHeaderTimeout: 5 * time.Second,
}

// Graceful shutdown
go serve(server)

quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("shutdown server ...")

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

if err := server.Shutdown(ctx); err != nil {
log.Fatal("server shutdown:", err)
if err := gracefulShutdown(server, 5*time.Second); err != nil {
log.Fatalln("graceful shutdown error", err)
}
<-ctx.Done()
log.Println("timeout of 5 seconds.")

log.Println("server exiting")
}

func serve(srv *http.Server) {
srvErr := srv.ListenAndServe()
if srvErr != nil && srvErr != http.ErrServerClosed {
log.Fatalf("listen: %s\n", srvErr)
log.Fatalf("listen error: %s\n", srvErr)
}
}

func gracefulShutdown(srv *http.Server, timeout time.Duration) error {
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

sig := <-quit
log.Printf("signal received: %v", sig)

ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

return srv.Shutdown(ctx)
}

0 comments on commit 2f8f3f9

Please sign in to comment.