-
-
Save hantoine/f2b1948814c007582081b1d4a7464559 to your computer and use it in GitHub Desktop.
Example of handling graceful shutdowns with gin-gonic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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