Sobes.tech
Middle+

Write a Graceful Shutdown mechanism for an HTTP server using channels and OS signal handling (Ctrl+C)

sobes.tech AI

Answer from AI

To implement a Graceful Shutdown of an HTTP server in Go, it is common to use a channel to intercept system signals (such as SIGINT when pressing Ctrl+C) and the Shutdown method from the net/http package, which allows the server to shut down properly, wait for active requests to complete, and free resources.

Example:

package main

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

func main() {
    srv := &http.Server{Addr: ":8080"}

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, world!"))
    })

    // Channel to receive OS signals
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

    go func() {
        <-quit
        log.Println("Shutting down server...")

        // Context with timeout for shutdown
        ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
        defer cancel()

        if err := srv.Shutdown(ctx); err != nil {
            log.Fatalf("Server forced to shutdown: %v", err)
        }
    }()

    log.Println("Server is ready to handle requests at :8080")
    if err := srv.ListenAndServe(); err != http.ErrServerClosed {
        log.Fatalf("Could not listen on :8080: %v", err)
    }

    log.Println("Server stopped")
}

In this example, the server starts and listens on port 8080. When a SIGINT or SIGTERM signal is received, a proper shutdown procedure with a 5-second timeout is initiated, during which the server completes processing current requests.

Write a Graceful Shutdown mechanism for an HTTP… - sobes.tech