Skip to content

Instantly share code, notes, and snippets.

@ivan3bx
Created September 20, 2017 05:32
Show Gist options
  • Save ivan3bx/b0f14449803ce5b0aa72afaa1dfc75e1 to your computer and use it in GitHub Desktop.
Save ivan3bx/b0f14449803ce5b0aa72afaa1dfc75e1 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, returning nil.
//
// - returns error if the server can not start
// - returns error if the server panics in a way that isn't
// otherwise handled by gin
// - no errors otherwise
func runServer(addr string, r *gin.Engine) error {
s := &http.Server{
Addr: addr,
Handler: r,
ReadTimeout: ReadTimeout,
WriteTimeout: WriteTimeout,
}
go func() {
log.Info("server starting")
if err := s.ListenAndServe(); err != http.ErrServerClosed {
panic(err)
}
}()
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c // block until signal received
log.Info("shutting down")
s.Shutdown(nil)
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment