# http：服务器已关闭

- **ID:** `go/http-server-shutdown-timeout`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

调用Server.Shutdown()时未设置正确的上下文超时，或服务器在活动请求仍在运行时被关闭，导致服务器返回'http: Server closed'错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.20 | active | — | — |
| 1.21 | active | — | — |

## 解决方案

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
})
   ```

## 无效尝试

- **** — Without a timeout, Shutdown() blocks indefinitely, and the server may never close, causing resource leaks. (70% 失败率)
- **** — os.Exit() bypasses deferred functions and prevents proper server shutdown, leading to incomplete cleanup. (90% 失败率)
