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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping Gin in a standard http.Server lets you set timeouts and control lifecycle explicitly.
- 2Blocking on an OS signal channel turns process termination into a controlled shutdown path.
- 3A deadline-bound context bounds how long you wait for in-flight requests before forcing exit.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/graceful-shutdown-for-a-gin-server-in-go-explained-go-176d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.