pkg/lifecycle 管理 HTTP 服务的启动、优雅关闭与生命周期回调。
http.Server 提供统一的启动/停机状态机。SIGINT / SIGTERM / SIGQUIT。type State
StateInitStateStartingStateRunningStateShuttingDownStateStoppedtype Hook func(ctx context.Context) errortype Manager
NewManager()SetShutdownTimeout(d)OnStart(hooks...)OnShutdown(hooks...)OnStopped(hooks...)Run(server, handler)Shutdown(ctx)State()Wait()30sSetShutdownTimeout(d):修改停机超时Run(server, handler):可传入自定义 http.Handler 覆盖 server.HandlerShutdown(ctx):触发优雅关闭,并解阻塞正在等待退出的 Run(server, handler);若关闭失败,错误由 Shutdown(ctx) 返回mgr := lifecycle.NewManager()
mgr.SetShutdownTimeout(10 * time.Second)
mgr.OnStart(func(ctx context.Context) error {
return nil
})
mgr.OnShutdown(func(ctx context.Context) error {
return db.Close()
})
server := &http.Server{Addr: ":8080", Handler: mux}
if err := mgr.Run(server, nil); err != nil {
panic(err)
}
gin.New() 默认创建一个 lifecycle.Manager。Engine.Run() 内部委托给 lifecycle.Manager.Run()。Engine.Shutdown(ctx) 内部委托给 lifecycle.Manager.Shutdown(ctx)。Engine.OnStart() / Engine.OnShutdown() / Engine.OnStopped() 用于透传注册生命周期回调。因此大多数应用无需直接操作该包,除非要自定义独立服务生命周期。