go runtime_error ai_generated true

http:服务器已关闭

http: Server closed

ID: go/http-server-shutdown-timeout

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 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)
    }
  2. 85% 成功率
    srv.RegisterOnShutdown(func() {
        // clean up resources
    })

无效尝试

常见但无效的做法:

  1. 70% 失败

    Without a timeout, Shutdown() blocks indefinitely, and the server may never close, causing resource leaks.

  2. 90% 失败

    os.Exit() bypasses deferred functions and prevents proper server shutdown, leading to incomplete cleanup.