golang example graceful shutdown

package main

import (

func main() {
    // Create a context that can be canceled with a signal
    ctx, cancel := context.WithCancel(context.Background())

    // Create a new server and set up a handler
    server := &http.Server{Addr: ":8080", Handler: http.HandlerFunc(handler)}

    // Set up a channel to receive OS signals
    signalChan := make(chan os.Signal, 1)
    signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)

    // Goroutine to handle graceful shutdown
    go func() {
        // Wait for a signal

        // Log the shutdown signal
        fmt.Println("Received shutdown signal. Shutting down gracefully...")

        // Cancel the context, triggering a graceful shutdown

        // Allow some time for connections to finish (adjust as needed)
        time.Sleep(5 * time.Second)

        // Shut down the server
        if err := server.Shutdown(ctx); err != nil {
            fmt.Println("Error during server shutdown:", err)

    // Start the server
    fmt.Println("Server is now running on :8080")
    if err := server.ListenAndServe(); err != http.ErrServerClosed {
        fmt.Println("Error starting server:", err)

func handler(w http.ResponseWriter, r *http.Request) {
    // Simulate some work
    time.Sleep(2 * time.Second)
    fmt.Fprintln(w, "Hello, this is the handler response!")