Skip to content

Instantly share code, notes, and snippets.

@hantoine
Forked from ivan3bx/graceful_httpserver.go
Last active May 4, 2023 18:21
Show Gist options
  • Save hantoine/f2b1948814c007582081b1d4a7464559 to your computer and use it in GitHub Desktop.
Save hantoine/f2b1948814c007582081b1d4a7464559 to your computer and use it in GitHub Desktop.
Example of handling graceful shutdowns with gin-gonic
// runServer will start the HTTPServer, handling graceful
// shutdown on receives SIGTERM / SIGINT.
func runServer(addr string, engine *gin.Engine) {
s := &http.Server{
Addr: addr,
Handler: engine.Handler(),
}
go func() {
log.Info("server starting")
if err := s.ListenAndServe(); err != http.ErrServerClosed {
panic(err)
}
}()
c := make(chan os.Signal, 2) // Need to be buffered, see https://pkg.go.dev/os/signal#Notify
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
<-c // block until signal received
ctx, releaseTimeout := context.WithTimeout(context.Background(), 5*time.Second)
defer releaseTimeout()
if err := server.Shutdown(ctx); err != nil {
log.Fatal("Server shutdown failed or timed out: ", err)
}
log.Println("Graceful shut down complete")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment