go
runtime_error
ai_generated
true
http: Server closed
ID: go/http-server-shutdown-timeout
80%Fix Rate
88%Confidence
0Evidence
2024-03-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.20 | active | — | — | — |
| 1.21 | active | — | — | — |
Root Cause
Server.Shutdown() is called without a proper context timeout, or the server is closed while active requests are still running, causing the server to return 'http: Server closed' error.
generic中文
调用Server.Shutdown()时未设置正确的上下文超时,或服务器在活动请求仍在运行时被关闭,导致服务器返回'http: Server closed'错误。
Workarounds
-
90% success
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := srv.Shutdown(ctx); err != nil { log.Fatal("Server forced to shutdown:", err) } -
85% success
srv.RegisterOnShutdown(func() { // clean up resources })
Dead Ends
Common approaches that don't work:
-
70% fail
Without a timeout, Shutdown() blocks indefinitely, and the server may never close, causing resource leaks.
-
90% fail
os.Exit() bypasses deferred functions and prevents proper server shutdown, leading to incomplete cleanup.