Backend Boilerplates go Intermediate

Go Graceful Shutdown

HTTP server that handles SIGTERM/SIGINT and drains in-flight requests before exiting.

go
package main

import (
    "context"; "log"; "net/http"; "os"; "os/signal"; "syscall"; "time"
)

func main() {
    srv := &http.Server{Addr: ":8080", Handler: http.DefaultServeMux}
    go func() { log.Fatal(srv.ListenAndServe()) }()

    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)
    <-quit

    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    srv.Shutdown(ctx)
    log.Println("Server exited")
}

Prerequisites

  • Go >= 1.21

Pro Tips

  • → Set timeout to match your longest request.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
go
Level
Intermediate
Read time
4 min
Published
Aug 2025
License
Commercial License

Newsletter

New modules every week, directly to your inbox.