From 0152dd1d3581ac63f3be78d72ea8866c75cb1d4f Mon Sep 17 00:00:00 2001 From: xfy Date: Mon, 13 Apr 2026 11:25:39 +0800 Subject: [PATCH] =?UTF-8?q?feat(server):=20=E6=B7=BB=E5=8A=A0=20StopWithTi?= =?UTF-8?q?meout=20=E6=96=B9=E6=B3=95=E6=94=AF=E6=8C=81=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E8=B6=85=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 StopWithTimeout 方法,支持传入自定义超时参数: - 替代原有固定 5s 超时的 Stop 方法 - timeout <= 0 时自动使用默认 5s - 原 Stop 方法标记为 Deprecated,内部调用 StopWithTimeout 为配置化关闭超时提供基础设施。 Co-Authored-By: Claude Opus 4.6 --- internal/server/server.go | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/internal/server/server.go b/internal/server/server.go index 2eb72f7..359c734 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -744,17 +744,26 @@ func (s *Server) registerProxyRoutes(router *handler.Router, serverCfg *config.S } } -// Stop 快速停止服务器。 +// StopWithTimeout 快速停止服务器(支持自定义超时)。 // // 立即停止服务器,不等待正在处理的请求完成。 // 停止所有健康检查器和访问日志中间件。 // +// 参数: +// - timeout: 快速关闭的最大等待时间 +// // 返回值: // - error: 停止过程中遇到的错误 // // 注意事项: // - 对于生产环境,建议使用 GracefulStop 实现优雅关闭 -func (s *Server) Stop() error { +// - timeout <= 0 时会使用默认 5s 超时 +func (s *Server) StopWithTimeout(timeout time.Duration) error { + // 防御性检查:如果 timeout <= 0,使用默认值 + if timeout <= 0 { + timeout = 5 * time.Second + } + s.running = false // 停止 Goroutine 池 @@ -785,8 +794,8 @@ func (s *Server) Stop() error { } if s.fastServer != nil { - // 快速停止也需要 timeout,防止无限等待空闲连接 - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // 使用传入的 timeout + ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() done := make(chan struct{}) @@ -807,6 +816,23 @@ func (s *Server) Stop() error { return nil } +// Stop 快速停止服务器(向后兼容,使用默认 5s 超时)。 +// +// 立即停止服务器,不等待正在处理的请求完成。 +// 停止所有健康检查器和访问日志中间件。 +// +// 返回值: +// - error: 停止过程中遇到的错误 +// +// 注意事项: +// - 对于生产环境,建议使用 GracefulStop 实现优雅关闭 +// - 此方法使用默认 5s 超时,如需自定义超时请使用 StopWithTimeout +// +// Deprecated: 使用 StopWithTimeout 替代以支持自定义超时 +func (s *Server) Stop() error { + return s.StopWithTimeout(5 * time.Second) +} + // GracefulStop 优雅停止服务器。 // // 等待正在处理的请求完成后再停止服务器,确保连接正常关闭。