golang http graceful shutdown

package main

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

func main() {
    // Create a context to handle the graceful shutdown
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    // Create a new HTTP server
    server := &http.Server{
        Addr: ":8080", // Specify the server address
    }

    // Create a goroutine to handle OS signals
    go func() {
        signalChannel := make(chan os.Signal, 1)
        signal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)
        <-signalChannel

        // Notify the context to cancel when a signal is received
        cancel()
    }()

    // Start the HTTP server in a separate goroutine
    go func() {
        if err := server.ListenAndServe(); err != http.ErrServerClosed {
            fmt.Printf("Error: %v\n", err)
        }
    }()

    // Wait for the context to be canceled (either by a signal or other events)
    <-ctx.Done()

    // Create a context with a timeout to wait for active connections to finish
    timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer timeoutCancel()

    // Shutdown the server gracefully, allowing active connections to finish
    if err := server.Shutdown(timeoutCtx); err != nil {
        fmt.Printf("Error during server shutdown: %v\n", err)
    } else {
        fmt.Println("Server shutdown completed")
    }
}