DEV Community

Clavin June
Clavin June

Posted on • Originally published at clavinjune.dev on

2 2

Golang HTTP Server Graceful Shutdown

Sunday Snippet #6 golang HTTP server graceful shutdown

package main

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

func createChannel() (chan os.Signal, func()) {
    stopCh := make(chan os.Signal, 1)
    signal.Notify(stopCh, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)

    return stopCh, func() {
        close(stopCh)
    }
}

func start(server *http.Server) {
    log.Println("application started")
    if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
        panic(err)
    } else {
        log.Println("application stopped gracefully")
    }
}

func shutdown(ctx context.Context, server *http.Server) {
    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel()

    if err := server.Shutdown(ctx); err != nil {
        panic(err)
    } else {
        log.Println("application shutdowned")
    }
}

func main() {
    log.SetFlags(log.Lshortfile)
    s := &http.Server{}
    go start(s)

    stopCh, closeCh := createChannel()
    defer closeCh()
    log.Println("notified:", <-stopCh)

    shutdown(context.Background(), s)
}
Enter fullscreen mode Exit fullscreen mode

runtime:

$ go run main.go
main.go:24: application started
^Cmain.go:50: notified: interrupt # ctrl+c
main.go:28: application stopped gracefully
main.go:39: application shutdowned
$
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay