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 theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
go
package middleware import ( "net/http"
A maintenance-mode gate in Gin
middleware
atomic-flag
concurrency
Intermediate
8 steps
typescript
import { Injectable, Logger, OnApplicationShutdown } from '@nestjs/common'; import { InjectRedis } from '@nestjs-modules/ioredis'; import Redis from 'ioredis'; import { DataSource } from 'typeorm';
Graceful shutdown hooks in NestJS
graceful-shutdown
lifecycle-hooks
dependency-injection
Intermediate
7 steps
go
func ServeVideo(c *gin.Context) { id := c.Param("id") video, err := videoRepo.FindByID(c.Request.Context(), id) if err != nil {
Streaming video files with Gin
http streaming
range requests
file serving
Intermediate
6 steps
go
package handler type LineItem struct { SKU string `json:"sku" binding:"required,alphanum"`
Structured validation errors in Gin
validation
json-binding
error-handling
Intermediate
8 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.