go
runtime_error
ai_generated
true
http:服务器已关闭
http: Server closed
ID: go/http-server-shutdown-timeout
80%修复率
88%置信度
0证据数
2024-03-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.20 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
调用Server.Shutdown()时未设置正确的上下文超时,或服务器在活动请求仍在运行时被关闭,导致服务器返回'http: Server closed'错误。
English
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.
解决方案
-
90% 成功率
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% 成功率
srv.RegisterOnShutdown(func() { // clean up resources })
无效尝试
常见但无效的做法:
-
70% 失败
Without a timeout, Shutdown() blocks indefinitely, and the server may never close, causing resource leaks.
-
90% 失败
os.Exit() bypasses deferred functions and prevents proper server shutdown, leading to incomplete cleanup.