http.ErrServerClosed
GoINFOCommonHTTP

http: Server closed

Quick Answer

Ignore http.ErrServerClosed when it is returned from ListenAndServe during planned shutdown.

What this means

Returned by Server.ListenAndServe after Server.Shutdown or Server.Close is called. It is expected during graceful shutdown and should not be treated as an error.

Why it happens
  1. 1Server.Shutdown called to initiate graceful shutdown
  2. 2Server.Close called to forcibly stop the server

Fix

Ignore during shutdown

Ignore during shutdown
if err := srv.ListenAndServe(); err != nil &&
    !errors.Is(err, http.ErrServerClosed) {
    log.Fatal(err)
}

Why this works

Filtering out ErrServerClosed prevents false fatal errors during planned shutdown.

Code examples
Detectgo
err := srv.ListenAndServe()
if errors.Is(err, http.ErrServerClosed) {
    fmt.Println("server stopped")
}
Graceful shutdowngo
ctx, cancel := context.WithTimeout(
    context.Background(), 5*time.Second)
defer cancel()
srv.Shutdown(ctx)
Signal handlinggo
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
srv.Shutdown(context.Background())
Sources
Official documentation ↗

Go standard library

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Go errors