go network_error ai_generated true

http: Server closed

ID: go/http-server-closed

Also available as: JSON · Markdown
90%Fix Rate
92%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

http.ErrServerClosed is returned by ListenAndServe after Shutdown() or Close() is called. This is expected behavior during graceful shutdown but confusing when treated as an unexpected error.

generic

Workarounds

  1. 95% success Check for http.ErrServerClosed and treat it as a normal shutdown
    if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
        log.Fatal(err)
    }

    Sources: https://pkg.go.dev/net/http#ErrServerClosed

  2. 92% success Implement graceful shutdown with signal handling
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
    <-quit
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    srv.Shutdown(ctx)

    Sources: https://pkg.go.dev/net/http#Server.Shutdown

Dead Ends

Common approaches that don't work:

  1. Wrap ListenAndServe in a retry loop 85% fail

    After Shutdown/Close, the server cannot be restarted — retrying ListenAndServe on a closed server will fail immediately again

Error Chain

Leads to:
Preceded by:
Frequently confused with: