竹简文档
初始化

服务运行时

xMain.Runner 统一启动 HTTP 服务并支持优雅关闭

服务运行时

xMain.Runner 用于统一启动 HTTP 服务、托管后台协程并在信号到达时优雅关闭。

import xMain "github.com/bamboo-services/bamboo-base-go/major/main"

Runner

runner.go
func Runner(
    reg *xReg.Reg,
    log *xLog.LogNamedLogger,
    routeFunc func(reg *xReg.Reg),
    goroutineFunc ...func(ctx context.Context, option ...any),
)

功能

  • 从环境变量读取 XLF_HOSTXLF_PORT 作为监听地址,默认 localhost:1118
  • 自动监听 SIGINT/SIGTERM,触发优雅关闭。
  • 支持注册路由函数。
  • 支持启动多个后台协程并统一等待退出。
  • HTTP 关闭超时时间为 30 秒。

参数说明

字段

类型

快速使用

main.go
package main

import (
    "context"

    xCtx "github.com/bamboo-services/bamboo-base-go/defined/context"
    xLog "github.com/bamboo-services/bamboo-base-go/common/log"
    xMain "github.com/bamboo-services/bamboo-base-go/major/main"
    xReg "github.com/bamboo-services/bamboo-base-go/major/register"
    xRegNode "github.com/bamboo-services/bamboo-base-go/major/register/node"
)

func main() {
    reg := xReg.Register(context.Background(), []xRegNode.RegNodeList{
        {Key: xCtx.DatabaseKey, Node: initDatabase},
        {Key: xCtx.RedisClientKey, Node: initRedis},
    })

    log := xLog.WithName(xLog.NamedMAIN)

    xMain.Runner(reg, log, registerRoute)
}

带后台任务示例

func runConsumer(ctx context.Context, option ...any) {
    for {
        select {
        case <-ctx.Done():
            return
        default:
            // 消费任务
        }
    }
}

func main() {
    // ... reg, log 初始化省略
    xMain.Runner(reg, log, registerRoute, runConsumer)
}

如需接入 gRPC(可选),请前往独立模块文档:gRPC 运行时

下一步

On this page