# server **Repository Path**: xgo-core/server ## Basic Information - **Project Name**: server - **Description**: server - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-04-22 - **Last Updated**: 2026-10-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # XGo Server `gitee.com/xgo-core/server` 是 XGo 应用的服务生命周期模块。它负责加载配置与日志,启动通过容器注入的服务,并在进程收到退出信号时统一关闭服务。 ## 功能 - 按固定顺序派发已注入的 HTTP、gRPC、metrics、pprof 和 tracing 服务生命周期,并由运行时初始化 command 和 event 模块。 - 基于依赖容器发现服务实现、HTTP 路由注册器和 gRPC 服务注册器。 - HTTP 服务基于 Gin,内置请求上下文注入和 OpenTelemetry 中间件。 - gRPC 服务支持通过接口注入注册服务,并支持优雅关闭。 - pprof 使用独立 Gin 服务,并通过 `github.com/gin-contrib/pprof` 暴露标准诊断路由。 - XXL-JOB executor 使用独立 Gin 服务,并基于官方 `github.com/xxl-job/xxl-job-executor-go` 执行器。 - 支持使用 OpenTelemetry 初始化链路追踪,并通过配置选择 Jaeger、SkyWalking 或 Zipkin exporter。 ## 快速开始 在应用入口调用 `server.Run()`: ```go package main import "gitee.com/xgo-core/server" func main() { server.Run() } ``` 内置服务会在包初始化时注册到依赖容器中。调用 `server.Run()` 前需要注入具体配置结构体,或通过 XGo config 模块加载这些配置,让容器自动装配到内置 server 实例上。 HTTP、链路追踪和 XXL-JOB 还需要 `configs.BaseConf` 提供通用服务元信息: ```go container.MustInject(&configs.BaseConf{ServiceName: "demo-service"}) container.MustInject(&configs.HTTPServerConf{Enable: true, Addr: ":8080"}) container.MustInject(&configs.GRPCServerConf{Enable: false}) container.MustInject(&configs.PprofServerConf{Enable: false}) container.MustInject(&configs.OpentracingConf{Enable: false}) container.MustInject(&configs.XxlServerConf{ Enable: false, AdminUrl: "http://127.0.0.1:8080/xxl-job-admin", }) ``` 不需要启动的服务请将 `enable` 设为 `false`。缺少必需配置会被视为启动错误,因为内置 server 实例无法被安全装配。 ## 运行时生命周期 `server.Run()` 先初始化配置、日志和数据库,再启动已注册的 server。内置的 command 与 event 模块会作为 `servers.ServerInterface` 实现注册,因此会与网络服务共用同一套生命周期。 所有注入的 `servers.ServerInterface` 实现会先按 `ServerOrder()` 升序排序,再派发生命周期调用。`Synchronous()` 返回 `true` 的初始化组件会在当前调用链中启动,必须在下一个生命周期回调派发前返回。返回 `false` 的组件会以一秒间隔放入受管 goroutine,运行时会等待其 `ServerStart` 返回。顺序值只保证派发顺序,并不等待低顺序 server 就绪。根 context 结束后,`ServerClose` 会按降序派发。 注入自定义生命周期组件时可指定顺序: ```go type CacheServer struct{} const cacheServerOrder = servers.HTTPServerOrder + 1 func (s *CacheServer) Synchronous() bool { return false } func (s *CacheServer) ServerOrder() int { return cacheServerOrder } func (s *CacheServer) ServerStart(ctx *xgocontext.XGoContext) error { <-ctx.Done() return nil } func (s *CacheServer) ServerClose(ctx *xgocontext.XGoContext) { } container.MustInject(&CacheServer{}) ``` ## HTTP 路由 实现并注入 `servers.RouterInterface` 即可注册 HTTP 路由: ```go type Router struct{} func (r *Router) RegisterHTTPRoutes(router gin.IRouter) { router.GET("/ping", func(ctx *gin.Context) { ctx.JSON(http.StatusOK, gin.H{"message": "pong"}) }) } ``` HTTP 服务使用 `configs.HTTPServerConf` 配置: ```json { "enable": true, "addr": ":8080", "read_timeout": 10, "write_timeout": 10, "idle_timeout": 10, "max_header_bytes": 20 } ``` 默认值: - 地址:`:8080` - 读超时:`10s` - 写超时:`10s` - 空闲超时:`10s` - 最大 header 字节数:`1 << 20` ## gRPC 服务 实现并注入 `servers.GRPCServiceInterface` 即可注册 gRPC 服务: ```go type GRPCRegistrar struct{} func (r *GRPCRegistrar) RegisterGRPCRoutes(server grpc.ServiceRegistrar) { pb.RegisterUserServiceServer(server, &UserService{}) } ``` gRPC 服务使用 `configs.GRPCServerConf` 配置: ```json { "enable": true, "addr": ":9090" } ``` 默认地址:`:9090`。 ### gRPC 服务注册中心 gRPC server 预留了服务注册中心扩展点。后续接入 Nacos、etcd 或其他注册中心时,只需要实现并注入 `servers.GRPCRegistryInterface`: ```go type Registry struct{} func (r *Registry) RegisterGRPCInstance(ctx *xgocontext.XGoContext, instance servers.GRPCRegistryInstance) error { // 注册 instance.Host、instance.Port、instance.ServiceName 和 instance.Metadata。 return nil } func (r *Registry) DeregisterGRPCInstance(ctx *xgocontext.XGoContext, instance servers.GRPCRegistryInstance) error { // 从注册中心移除当前实例。 return nil } ``` 框架会在 TCP listener 和 gRPC 路由准备完成后调用 `RegisterGRPCInstance`,并在服务关闭时调用 `DeregisterGRPCInstance`。 ## pprof pprof 服务运行在独立 Gin engine 上,并在 `/debug/pprof` 下暴露标准 pprof 路由。它分析的是整个 Go 进程,而不是只分析 pprof engine 本身。 pprof 服务使用 `configs.PprofServerConf` 配置: ```json { "enable": true, "addr": "127.0.0.1:6060" } ``` 默认地址:`127.0.0.1:6060`。 ## XXL-JOB Executor XXL-JOB executor 运行在独立 Gin HTTP server 上。它使用官方 `github.com/xxl-job/xxl-job-executor-go` executor,并通过 Gin 暴露执行器接口。 实现并注入 `servers.XxlJobInterface` 即可注册任务: ```go type DemoJob struct{} func (j *DemoJob) Job() string { return "demo.job" } func (j *DemoJob) Handle(ctx *xgocontext.XGoContext, param *xxl.RunReq) string { return "ok" } ``` XXL-JOB 服务使用 `configs.XxlServerConf` 配置: ```json { "enable": true, "admin_url": "http://127.0.0.1:8080/xxl-job-admin", "token": "", "addr": "0.0.0.0:9999", "read_timeout": 10, "write_timeout": 86400, "idle_timeout": 10, "max_header_bytes": 20 } ``` 默认值: - executor 监听地址:由 `addr` 配置 - 读超时:`10s` - 写超时:`86400s` - 空闲超时:`10s` - 最大 header 字节数:`1 << 20` `admin_url` 必须是 XXL-JOB admin 的基础地址。`addr` 必须配置为合法的 `host:port` 监听地址,例如 `0.0.0.0:9999`。长任务超时仍应通过 XXL-JOB 任务超时配置控制,而不是依赖 HTTP server timeout。 ## 链路追踪配置 链路追踪通过 `configs.OpentracingConf` 配置。`driver` 选择当前启用的追踪后端,`exporter` 保存不同后端的独立配置。 支持的 driver: - `jaeger` - `skywalking` - `zipkin` 示例: ```json { "enable": true, "driver": "jaeger", "sample_ratio": 1, "shutdown_timeout": 10, "exporter": { "jaeger": { "endpoint": "localhost:4317", "insecure": true, "timeout": 10 }, "skywalking": { "endpoint": "localhost:11800", "insecure": true, "timeout": 10 }, "zipkin": { "endpoint": "http://localhost:9411/api/v2/spans", "timeout": 10 } } } ``` 默认 endpoint: - Jaeger:`localhost:4317` - SkyWalking:`localhost:11800` - Zipkin:`http://localhost:9411/api/v2/spans` ## 开发 格式化和测试: ```bash go fmt ./... go test ./... ``` 英文文档见 [README.md](README.md)。