go 49 lines · 6 steps

Graceful shutdown for a Gin server in Go

Run a Gin HTTP server that drains in-flight requests when it receives a termination signal.

Explained by highlit
1package main
2 
3import (
4 "context"
5 "errors"
6 "log"
7 "net/http"
8 "os"
9 "os/signal"
10 "syscall"
11 "time"
12 
13 "github.com/gin-gonic/gin"
14)
15 
16func main() {
17 router := gin.Default()
18 
19 router.GET("/healthz", func(c *gin.Context) {
20 c.JSON(http.StatusOK, gin.H{"status": "ok"})
21 })
22 
23 srv := &http.Server{
24 Addr: ":8080",
25 Handler: router,
26 ReadTimeout: 15 * time.Second,
27 WriteTimeout: 15 * time.Second,
28 }
29 
30 go func() {
31 if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
32 log.Fatalf("listen: %v", err)
33 }
34 }()
35 
36 quit := make(chan os.Signal, 1)
37 signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
38 <-quit
39 log.Println("shutting down server...")
40 
41 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
42 defer cancel()
43 
44 if err := srv.Shutdown(ctx); err != nil {
45 log.Fatalf("forced shutdown: %v", err)
46 }
47 
48 log.Println("server exited cleanly")
49}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Wrapping Gin in a standard http.Server lets you set timeouts and control lifecycle explicitly.
  2. 2Blocking on an OS signal channel turns process termination into a controlled shutdown path.
  3. 3A deadline-bound context bounds how long you wait for in-flight requests before forcing exit.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Graceful shutdown for a Gin server in Go — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code