refactor(server): 移除废弃的 Stop 方法,更新测试使用 StopWithTimeout

移除 deprecated Stop() 方法,测试代码改用 StopWithTimeout。
testutil.go 更新为支持 servers 配置格式。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
xfy 2026-04-15 12:48:49 +08:00
parent 2bc13dd03b
commit f04f804834
3 changed files with 29 additions and 34 deletions

View File

@ -416,15 +416,17 @@ func (s *Server) Start() error {
// 初始化错误页面管理器
var err error
s.errorPageManager, err = initErrorPageManager(&s.config.Server.Security.ErrorPage)
if err != nil {
return err
}
if len(s.config.Servers) > 0 {
s.errorPageManager, err = initErrorPageManager(&s.config.Servers[0].Security.ErrorPage)
if err != nil {
return err
}
// 初始化 Lua 引擎
s.luaEngine, err = initLuaEngine(s.config.Server.Lua)
if err != nil {
return err
// 初始化 Lua 引擎
s.luaEngine, err = initLuaEngine(s.config.Servers[0].Lua)
if err != nil {
return err
}
}
// 根据模式选择启动方式
@ -992,23 +994,6 @@ func (s *Server) StopWithTimeout(timeout time.Duration) error {
return nil
}
// Stop 快速停止服务器(向后兼容,使用默认 5s 超时)。
//
// 立即停止服务器,不等待正在处理的请求完成。
// 停止所有健康检查器和访问日志中间件。
//
// 返回值:
// - error: 停止过程中遇到的错误
//
// 注意事项:
// - 对于生产环境,建议使用 GracefulStop 实现优雅关闭
// - 此方法使用默认 5s 超时,如需自定义超时请使用 StopWithTimeout
//
// Deprecated: 使用 StopWithTimeout 替代以支持自定义超时
func (s *Server) Stop() error {
return s.StopWithTimeout(5 * time.Second)
}
// GracefulStop 优雅停止服务器。
//
// 等待正在处理的请求完成后再停止服务器,确保连接正常关闭。

View File

@ -64,9 +64,9 @@ func TestStopWithoutServer(t *testing.T) {
s := New(cfg)
// 在未启动时调用 Stop应返回 nil
err := s.Stop()
err := s.StopWithTimeout(5 * time.Second)
if err != nil {
t.Errorf("Stop() on non-started server returned error: %v", err)
t.Errorf("StopWithTimeout() on non-started server returned error: %v", err)
}
}
@ -97,11 +97,11 @@ func TestStopAfterStop(t *testing.T) {
s := New(cfg)
// 多次调用 Stop 应该都是安全的
// 多次调用 StopWithTimeout 应该都是安全的
for i := 0; i < 3; i++ {
err := s.Stop()
err := s.StopWithTimeout(5 * time.Second)
if err != nil {
t.Errorf("Stop() call %d returned error: %v", i+1, err)
t.Errorf("StopWithTimeout() call %d returned error: %v", i+1, err)
}
}
}
@ -550,9 +550,9 @@ func TestServer_StopWithNilFastServer(t *testing.T) {
s := New(cfg)
s.fastServer = nil
err := s.Stop()
err := s.StopWithTimeout(5 * time.Second)
if err != nil {
t.Errorf("Stop with nil fastServer should succeed: %v", err)
t.Errorf("StopWithTimeout with nil fastServer should succeed: %v", err)
}
}

View File

@ -102,8 +102,18 @@ func NewTestServerWithOptions(cfg *config.Config, opts *TestServerOptions) *Serv
func MustStartTestServer(cfg *config.Config) *Server {
s := New(cfg)
// 在测试环境中使用随机端口避免冲突
if cfg.Server.Listen == "" || cfg.Server.Listen == ":80" {
cfg.Server.Listen = "127.0.0.1:0"
listenAddr := ""
if len(cfg.Servers) > 0 {
listenAddr = cfg.Servers[0].Listen
} else {
listenAddr = cfg.Server.Listen
}
if listenAddr == "" || listenAddr == ":80" {
if len(cfg.Servers) > 0 {
cfg.Servers[0].Listen = "127.0.0.1:0"
} else {
cfg.Server.Listen = "127.0.0.1:0"
}
}
// 使用 goroutine 启动服务器以避免阻塞