bootstrap

package module
v0.0.0-...-47b81fd Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 17 Imported by: 0

README

GoWind Bootstrap · 声明式应用引导框架

English | 中文 | 日本語

Go Version go-wind Protobuf Cobra License PRs Welcome


项目亮点

  • 声明式配置驱动:基于 Protobuf 定义的 BootstrapConfig,一份 YAML 配置即可描述完整的应用拓扑——传输层、配置中心、注册发现、日志、追踪、指标、消息代理
  • SPI 插件注册机制:通过 init() + 空导入实现 Builder 自注册,零胶水代码即可扩展新组件
  • 声明式中间件编排:HTTP/gRPC 中间件通过配置启用和参数化,无需手写一行中间件初始化代码
  • 三层封装,灵活切换:从一行代码启动的全密封模式,到手写 Builder 的完全开放模式,按需选择
  • 多模块依赖隔离:每个适配子包独立 go.mod,用户只引入需要的适配器,不污染依赖树
  • Cobra 命令行集成:内置命令行支持,通过 -c 参数指定配置文件,开箱即用
  • 多格式配置支持:自动识别 YAML / JSON / Protobuf 二进制格式,平滑迁移

快速开始

安装
go get github.com/tx7do/go-wind-bootstrap
最简示例

config.yaml

app:
  id: my-service
  name: my-service
  version: "1.0.0"
  env: development

server:
  http:
    addr: ":8080"
    middleware:
      recovery: {}
      cors: {}
      logging: {}

logger:
  type: zap
  zap:
    level: info
    format: json

main.go

package main

import (
    "fmt"
    "net/http"
    "os"

    bootstrap "github.com/tx7do/go-wind-bootstrap"
    _ "github.com/tx7do/go-wind-bootstrap/log/zap"
    httpAdapter "github.com/tx7do/go-wind-bootstrap/transport/http"
)

func main() {
    httpAdapter.RegisterServerSetup(func(srv *httpAdapter.Server) {
        srv.GET("/", func(w http.ResponseWriter, r *http.Request) {
            _, _ = fmt.Fprintf(w, "Hello, GoWind!\n")
        })
    })

    if err := bootstrap.RunAppWithFlags(bootstrap.NewCommandFlags()); err != nil {
        os.Exit(1)
    }
}
# 启动
go run main.go

# 指定配置文件
go run main.go -c /path/to/config.yaml

# 测试
curl http://localhost:8080

设计理念

配置即应用

go-wind-bootstrap 的核心思想是声明式配置驱动。应用的完整拓扑——从传输层到消息代理——全部通过一份 Protobuf 定义的 BootstrapConfig 描述。引导引擎读取配置,通过注册的 Builder 自动组装 wind.App

BootstrapConfig → Builder Registry → wind.Option Chain → wind.App
SPI 自注册模式

每个适配子包通过 init() + 空导入将 Builder 注册到全局注册表。用户只需导入对应的适配器包,框架自动完成组件创建:

import (
    _ "github.com/tx7do/go-wind-bootstrap/log/zap"           // 注册 Zap Logger Builder
    _ "github.com/tx7do/go-wind-bootstrap/transport/http"     // 注册 HTTP Server Builder
    _ "github.com/tx7do/go-wind-bootstrap/transport/grpc"     // 注册 gRPC Server Builder
)
声明式中间件

HTTP 和 gRPC 中间件通过配置文件的 optional 字段启用,参数也通过配置传入。无需编写初始化代码:

server:
  http:
    addr: ":8080"
    middleware:
      recovery:
        stack_trace: true
      cors:
        allowed_origins:
          - "*"
        allowed_methods:
          - GET
          - POST
      logging:
        skip_paths:
          - /health
      request_id:
        header_name: X-Request-ID

三层 API 封装

层次 API 适用场景
全密封 RunApp / RunAppWithFlags 一行代码启动,自动处理信号监听、配置加载、生命周期
半密封 BootstrapWithContext 需要访问 Context(配置、App、Cancel)进行定制
开放 Bootstrap / Run 完全手动控制每一步,适合高级场景
全密封模式
// 最简单:一行启动
bootstrap.RunApp("config.yaml")

// 带 Cobra 命令行
bootstrap.RunAppWithFlags(bootstrap.NewCommandFlags())
半密封模式
bctx, err := bootstrap.BootstrapWithContext(nil, cfg)
if err != nil {
    log.Fatal(err)
}
defer bctx.Cleanup()

// 可在运行前操作 Context
fmt.Println(bctx.Config().GetApp().GetName())

bctx.App().Run(bctx)
开放模式
cfg, _ := bootstrap.LoadConfigFromFile("config.yaml")
app, cleanup, err := bootstrap.Bootstrap(ctx, cfg)
if err != nil {
    log.Fatal(err)
}
defer cleanup()

app.Run(ctx)

架构总览

graph TB
    Config["BootstrapConfig<br/>YAML / JSON / Protobuf"]
    Engine["Bootstrap Engine<br/>Builder Registry + Resolver"]
    App["wind.App<br/>生命周期管理"]

    Config -->|"加载配置"| Engine
    Engine -->|"Server Builder"| Server["Server<br/>HTTP · gRPC · TCP · WebSocket · ..."]
    Engine -->|"Log Builder"| Logger["Logger<br/>Zap · Zerolog · Slog · ..."]
    Engine -->|"Registry Action"| Registry["Registry<br/>Consul · Etcd · Nacos · ..."]
    Engine -->|"Config Action"| ConfigSrc["Config Source<br/>File · Etcd · Nacos · ..."]
    Engine -->|"Tracer Builder"| Tracer["Tracer<br/>OTLP"]
    Engine -->|"Metrics Builder"| Metrics["Metrics<br/>Prometheus · OTLP"]
    Engine -->|"Broker Builder"| Broker["Broker<br/>Kafka · RabbitMQ · Redis · ..."]
    Server --> App
    Logger --> App
    Registry --> App
    ConfigSrc --> App
    Tracer --> App
    Metrics --> App
    Broker --> App

支持的组件

传输层(Server)
类型 常量 适配器
HTTP http transport/http
gRPC grpc transport/grpc
HTTP/3 http3
GraphQL graphql
SSE sse
WebSocket websocket
TCP tcp
UDP udp
KCP kcp
Thrift thrift
tRPC trpc
WebTransport webtransport
日志(Logger)
类型 常量
Zap ✅ zap
Zerolog zerolog
Slog slog
Logrus logrus
Charm charm
Phuslu phuslu
Loki loki
Sentry sentry
阿里云 aliyun
腾讯云 tencent
CloudWatch cloudwatch
配置中心(Config)
类型 常量
File file
Etcd etcd
Nacos nacos
Consul consul
Apollo apollo
Kubernetes kubernetes
Redis redis
Zookeeper zookeeper
Vault vault
Polaris polaris
服务注册发现(Registry)
类型 常量
Consul consul
Etcd etcd
Nacos nacos
Zookeeper zookeeper
Polaris polaris
Eureka eureka
Kubernetes kubernetes
ServiceComb service_comb
分布式追踪(Tracer)
类型 常量
OTLP otlp
指标监控(Metrics)
类型 常量
Prometheus prometheus
OTLP otlp
消息代理(Broker)
类型 常量
Kafka kafka
RabbitMQ rabbitmq
Redis redis
NATS nats
MQTT mqtt
Pulsar pulsar
Azure Service Bus azuresb
Google Pub/Sub gcpubsub
NSQ nsq
RocketMQ rocketmq
SQS sqs
STOMP stomp

声明式中间件

HTTP 中间件
中间件 配置字段 说明
Recovery recovery 异常恢复,可选 stack_trace
CORS cors 跨域资源共享,支持 allowed_origins/methods/headers
Logging logging 请求日志,可选 skip_paths
Request ID request_id 请求 ID 注入,可选 header_name
Tracing tracing OpenTelemetry 链路追踪
Rate Limit rate_limit 限流
Timeout timeout 请求超时
gRPC 中间件
中间件 配置字段 说明
Recovery recovery 异常恢复
Logging logging 请求日志
Tracing tracing OpenTelemetry 链路追踪
Validate validate 请求校验

路由注册

追加式注册(推荐)

适配器提供 RegisterServerSetup 追加式注册 API,支持代码生成器和手写代码共存:

// generated_routes.go(代码生成器自动生成)
func init() {
    httpAdapter.RegisterServerSetup(func(srv *httpAdapter.Server) {
        srv.GET("/v1/users", listUsers)
        srv.POST("/v1/users", createUser)
    })
}
// main.go(用户手写代码)
func init() {
    httpAdapter.RegisterServerSetup(func(srv *httpAdapter.Server) {
        srv.GET("/health", healthCheck)
    })
}
gRPC 服务注册
grpcAdapter.RegisterServiceRegistrar(func(srv *grpc.Server) {
    pb.RegisterGreeterServer(srv, &greeterService{})
})

项目结构

go-wind-bootstrap/
├── conf/                        # 独立 go.mod · Protobuf 配置定义
│   └── proto/bootstrap/v1/      # .proto 源文件
│       ├── bootstrap.proto      # 顶层 BootstrapConfig
│       ├── app.proto            # 应用元数据
│       ├── server.proto         # 传输层 + 中间件配置
│       ├── config.proto         # 配置中心
│       ├── registry.proto       # 服务注册发现
│       ├── log.proto            # 日志系统
│       ├── tracer.proto         # 分布式追踪
│       ├── metrics.proto        # 指标监控
│       └── broker.proto         # 消息代理
├── *.go                         # 根 go.mod · 引导引擎核心
│   ├── bootstrap.go             # 入口:Bootstrap / Run / RunApp
│   ├── builder.go               # Builder 注册表(SPI)
│   ├── context.go               # Context 生命周期封装
│   ├── cli.go                   # Cobra 命令行封装
│   ├── types.go                 # 组件类型常量
│   ├── server_builder.go        # Server 解析器
│   ├── config_builder.go        # Config 解析器
│   ├── registry_builder.go      # Registry 解析器
│   ├── log_builder.go           # Logger 解析器
│   ├── tracer_builder.go        # Tracer 解析器
│   ├── metrics_builder.go       # Metrics 解析器
│   └── broker_builder.go        # Broker 解析器
├── log/zap/                     # 独立 go.mod · Zap Logger 适配器
├── transport/http/              # 独立 go.mod · HTTP 适配器 + 中间件 + std driver
├── transport/grpc/              # 独立 go.mod · gRPC 适配器 + 中间件
└── _examples/
    ├── quickstart/              # 最简示例:一行代码启动
    ├── yaml_config/             # YAML 配置加载示例
    └── custom_builder/          # 自定义 Builder 示例

技术栈

层级 技术 说明
语言 Go 1.22+ 高性能编译型语言
框架 go-wind 微服务生命周期骨架
插件 go-wind-plugins 可插拔功能模块库
配置定义 Protobuf + buf.build 声明式配置,契约优先
配置格式 YAML / JSON / Protobuf Binary 多格式自动识别
命令行 Cobra CLI 参数解析

扩展自定义 Builder

当内置适配器不满足需求时,可以注册自定义 Builder:

// 注册自定义 Registry Builder
bootstrap.MustRegisterRegistryAction(bootstrap.RegistryTypeConsul,
    func(ctx context.Context, appCfg *v1.App, endpoints []string) (func(), error) {
        // 创建 Consul 注册中心...
        return func() { /* cleanup */ }, nil
    },
)

// 注册自定义 Broker Builder
bootstrap.MustRegisterBrokerBuilder(bootstrap.BrokerTypeKafka,
    func(ctx context.Context, cfg *v1.Broker) (func(), error) {
        // 创建 Kafka Broker...
        return func() { /* cleanup */ }, nil
    },
)

相关项目

项目 说明
go-wind 微服务生命周期骨架
go-wind-plugins 可插拔功能模块库

License

MIT License

Documentation

Overview

Package bootstrap provides a declarative application bootstrapper for go-wind.

It reads a [BootstrapConfig] (defined via Protobuf) and assembles the corresponding go-wind [App] with the right combination of servers, registries, config sources, loggers, tracers, metrics, and brokers from go-wind-plugins.

The core flow is:

BootstrapConfig → Builder registry → wind.Option chain → wind.App

Package bootstrap provides builder registration for all plugin domains.

Each plugin domain (server, config, registry, log, tracer, metrics, broker) maintains a map of string-keyed builder functions. The key is a lowercase type string (e.g. "consul", "zap") matching the JSON config value. Built-in builders are registered via init() in provider packages. Users can register custom builders to extend the framework.

Index

Constants

View Source
const (
	ServerTypeHTTP         = "http"
	ServerTypeHTTP3        = "http3"
	ServerTypeGRPC         = "grpc"
	ServerTypeGraphQL      = "graphql"
	ServerTypeSSE          = "sse"
	ServerTypeWebSocket    = "websocket"
	ServerTypeTCP          = "tcp"
	ServerTypeUDP          = "udp"
	ServerTypeKCP          = "kcp"
	ServerTypeThrift       = "thrift"
	ServerTypeTRPC         = "trpc"
	ServerTypeWebTransport = "webtransport"
	ServerTypeCron         = "cron"
	ServerTypeHPTimer      = "hptimer"
	ServerTypeMCP          = "mcp"
	ServerTypeSignalR      = "signalr"
	ServerTypeSocketIO     = "socketio"
	ServerTypeWebRTC       = "webrtc"
	ServerTypeAsynq        = "asynq"
	ServerTypeMachinery    = "machinery"

	// Broker-based transport servers.
	ServerTypeKafka    = "kafka"
	ServerTypeRabbitMQ = "rabbitmq"
	ServerTypeRedis    = "redis"
	ServerTypeNATS     = "nats"
	ServerTypeMQTT     = "mqtt"
	ServerTypePulsar   = "pulsar"
	ServerTypeActiveMQ = "activemq"
	ServerTypeAzureSB  = "azuresb"
	ServerTypeNSQ      = "nsq"
	ServerTypeRocketMQ = "rocketmq"
	ServerTypeSQS      = "sqs"
)

Server type 常量,用于注册 Builder 时的 key。

View Source
const (
	ConfigTypeFile       = "file"
	ConfigTypeFs         = "fs"
	ConfigTypeEtcd       = "etcd"
	ConfigTypeNacos      = "nacos"
	ConfigTypeConsul     = "consul"
	ConfigTypeApollo     = "apollo"
	ConfigTypeKubernetes = "kubernetes"
	ConfigTypeRedis      = "redis"
	ConfigTypeZookeeper  = "zookeeper"
	ConfigTypeVault      = "vault"
	ConfigTypeHTTP       = "http"
	ConfigTypeEnv        = "env"
	ConfigTypeOSS        = "oss"
	ConfigTypePolaris    = "polaris"
)

Config type 常量,用于注册 ConfigAction 时的 key。

View Source
const (
	RegistryTypeConsul      = "consul"
	RegistryTypeEtcd        = "etcd"
	RegistryTypeNacos       = "nacos"
	RegistryTypeZookeeper   = "zookeeper"
	RegistryTypePolaris     = "polaris"
	RegistryTypeEureka      = "eureka"
	RegistryTypeKubernetes  = "kubernetes"
	RegistryTypeServiceComb = "service_comb"
)

Registry type 常量。

View Source
const (
	LoggerTypeZap        = "zap"
	LoggerTypeZerolog    = "zerolog"
	LoggerTypeSlog       = "slog"
	LoggerTypeLogrus     = "logrus"
	LoggerTypeCharm      = "charm"
	LoggerTypePhuslu     = "phuslu"
	LoggerTypeGlog       = "glog"
	LoggerTypeHclog      = "hclog"
	LoggerTypeFluent     = "fluent"
	LoggerTypeLoki       = "loki"
	LoggerTypeSentry     = "sentry"
	LoggerTypeAliyun     = "aliyun"
	LoggerTypeTencent    = "tencent"
	LoggerTypeCloudWatch = "cloudwatch"
)

Logger type 常量。

View Source
const (
	MetricsTypePrometheus = "prometheus"
	MetricsTypeOTLP       = "otlp"
)

Metrics type 常量。

View Source
const (
	BrokerTypeKafka    = "kafka"
	BrokerTypeRabbitMQ = "rabbitmq"
	BrokerTypeRedis    = "redis"
	BrokerTypeNATS     = "nats"
	BrokerTypeMQTT     = "mqtt"
	BrokerTypePulsar   = "pulsar"
	BrokerTypeAzureSB  = "azuresb"
	BrokerTypeGCPubSub = "gcpubsub"
	BrokerTypeNSQ      = "nsq"
	BrokerTypeRocketMQ = "rocketmq"
	BrokerTypeSQS      = "sqs"
	BrokerTypeSTOMP    = "stomp"
	BrokerTypeActiveMQ = "activemq"
)

Broker type 常量,用于注册 BrokerBuilder 时的 key。

View Source
const (
	StorageTypeMinio = "minio"
	StorageTypeS3    = "s3"
)

Storage type 常量,用于注册 StorageBuilder 时的 key。

View Source
const (
	AiTypeOpenAI      = "openai"
	AiTypeLangChainGo = "langchaingo"
	AiTypeEino        = "eino"
)

AI type 常量,用于注册 AiBuilder 时的 key。

View Source
const (
	WorkflowTypeTemporal    = "temporal"
	WorkflowTypeArgo        = "argo"
	WorkflowTypeConductor   = "conductor"
	WorkflowTypeGoWorkflows = "goworkflows"
)

Workflow type 常量,用于注册 WorkflowBuilder 时的 key。

View Source
const (
	CacheTypeLocal = "local"
	CacheTypeRedis = "redis"
)

Cache type 常量,用于注册 CacheBuilder 时的 key。

View Source
const (
	ScriptEngineLua        = "lua"
	ScriptEngineJavaScript = "javascript"
	ScriptEngineGPython    = "gpython"
	ScriptEngineYaegi      = "yaegi"
	ScriptEngineWazero     = "wazero"
	ScriptEngineCEL        = "cel"
	ScriptEngineExpr       = "expr"
	ScriptEngineStarlark   = "starlark"
	ScriptEngineTcl        = "tcl"
)

Script Engine type 常量。

View Source
const (
	DatabaseTypeGorm          = "gorm"
	DatabaseTypeMongodb       = "mongodb"
	DatabaseTypeClickhouse    = "clickhouse"
	DatabaseTypeDoris         = "doris"
	DatabaseTypeElasticsearch = "elasticsearch"
	DatabaseTypeOpensearch    = "opensearch"
	DatabaseTypeInfluxdb      = "influxdb"
	DatabaseTypeCassandra     = "cassandra"
)

Database type 常量,用于注册 DatabaseBuilder 时的 key。

View Source
const (
	TracerTypeOTLP = "otlp"
)

Tracer type 常量。

Variables

This section is empty.

Functions

func Bootstrap

func Bootstrap(ctx context.Context, cfg *v1.BootstrapConfig) (*wind.App, map[string]any, map[string]any, map[string]any, map[string]any, map[string]any, map[string]any, map[string]any, func(), error)

Bootstrap reads a [BootstrapConfig], resolves all configured subsystems through the builder registry, constructs a *wind.App, and returns it along with a map of broker instances keyed by type name and a cleanup function.

The caller is responsible for calling wind.App.Run.

cleanup must be called after the app stops to release resources (e.g. deregister from registry, flush tracers).

The broker map (first return value) may be nil if no broker is configured. Use the type key to look up a specific broker instance:

b, ok := brokers[bootstrap.BrokerTypeKafka]
if ok { /* use b as your kafka broker */ }

func ListAiBuilders

func ListAiBuilders() []string

ListAiBuilders returns all registered AI type names.

func ListBrokerBuilders

func ListBrokerBuilders() []string

ListBrokerBuilders returns all registered broker type names.

func ListCacheBuilders

func ListCacheBuilders() []string

ListCacheBuilders returns all registered cache type names.

func ListConfigActions

func ListConfigActions() []string

ListConfigActions returns all registered config type names.

func ListDatabaseBuilders

func ListDatabaseBuilders() []string

ListDatabaseBuilders returns all registered database type names.

func ListLogBuilders

func ListLogBuilders() []string

ListLogBuilders returns all registered log type names.

func ListMetricsBuilders

func ListMetricsBuilders() []string

ListMetricsBuilders returns all registered metrics type names.

func ListRegistryActions

func ListRegistryActions() []string

ListRegistryActions returns all registered registry type names.

func ListScriptEngineBuilders

func ListScriptEngineBuilders() []string

ListScriptEngineBuilders returns all registered script engine type names.

func ListServerBuilders

func ListServerBuilders() []string

ListServerBuilders returns all registered server type names.

func ListStorageBuilders

func ListStorageBuilders() []string

ListStorageBuilders returns all registered storage type names.

func ListTracerBuilders

func ListTracerBuilders() []string

ListTracerBuilders returns all registered tracer type names.

func ListWorkflowBuilders

func ListWorkflowBuilders() []string

ListWorkflowBuilders returns all registered workflow type names.

func LoadConfig

func LoadConfig(data []byte) (*v1.BootstrapConfig, error)

LoadConfig unmarshals a JSON-encoded [BootstrapConfig].

func LoadConfigBinary

func LoadConfigBinary(data []byte) (*v1.BootstrapConfig, error)

LoadConfigBinary unmarshals a binary-encoded (proto wire format) [BootstrapConfig].

func LoadConfigFromFile

func LoadConfigFromFile(path string) (*v1.BootstrapConfig, error)

LoadConfigFromFile reads a [BootstrapConfig] from the given file path. It auto-detects the format by extension:

  • .yaml, .yml → YAML
  • .json → JSON
  • .bin, .pb → Protobuf binary

func LoadConfigFromYAML

func LoadConfigFromYAML(data []byte) (*v1.BootstrapConfig, error)

LoadConfigFromYAML unmarshals a YAML-encoded [BootstrapConfig].

func MustRegisterAiBuilder

func MustRegisterAiBuilder(typ string, b AiBuilder)

MustRegisterAiBuilder panics on error.

func MustRegisterBrokerBuilder

func MustRegisterBrokerBuilder(typ string, b BrokerBuilder)

MustRegisterBrokerBuilder panics on error.

func MustRegisterCacheBuilder

func MustRegisterCacheBuilder(typ string, b CacheBuilder)

MustRegisterCacheBuilder panics on error.

func MustRegisterConfigAction

func MustRegisterConfigAction(typ string, a ConfigAction)

MustRegisterConfigAction panics on error.

func MustRegisterDatabaseBuilder

func MustRegisterDatabaseBuilder(typ string, b DatabaseBuilder)

MustRegisterDatabaseBuilder panics on error.

func MustRegisterLogBuilder

func MustRegisterLogBuilder(typ string, b LogBuilder)

MustRegisterLogBuilder panics on error.

func MustRegisterMetricsBuilder

func MustRegisterMetricsBuilder(typ string, b MetricsBuilder)

MustRegisterMetricsBuilder panics on error.

func MustRegisterRegistryAction

func MustRegisterRegistryAction(typ string, a RegistryAction)

MustRegisterRegistryAction panics on error.

func MustRegisterScriptEngineBuilder

func MustRegisterScriptEngineBuilder(typ string, b ScriptEngineBuilder)

MustRegisterScriptEngineBuilder panics on error.

func MustRegisterServerBuilder

func MustRegisterServerBuilder(typ string, b ServerBuilder)

MustRegisterServerBuilder panics on error. Intended for init().

func MustRegisterStorageBuilder

func MustRegisterStorageBuilder(typ string, b StorageBuilder)

MustRegisterStorageBuilder panics on error.

func MustRegisterTracerBuilder

func MustRegisterTracerBuilder(typ string, b TracerBuilder)

MustRegisterTracerBuilder panics on error.

func MustRegisterWorkflowBuilder

func MustRegisterWorkflowBuilder(typ string, b WorkflowBuilder)

MustRegisterWorkflowBuilder panics on error.

func NewRootCmd

func NewRootCmd(f *CommandFlags, runE func(cmd *cobra.Command, args []string) error) *cobra.Command

NewRootCmd creates the root cobra command with the standard bootstrap flags. The runE function is called after flags are parsed.

func RegisterAiBuilder

func RegisterAiBuilder(typ string, b AiBuilder) error

RegisterAiBuilder registers an AI builder for the given type string.

func RegisterBrokerBuilder

func RegisterBrokerBuilder(typ string, b BrokerBuilder) error

RegisterBrokerBuilder registers a broker builder for the given type string.

func RegisterCacheBuilder

func RegisterCacheBuilder(typ string, b CacheBuilder) error

RegisterCacheBuilder registers a cache builder for the given type string.

func RegisterConfigAction

func RegisterConfigAction(typ string, a ConfigAction) error

RegisterConfigAction registers a config action for the given type string.

func RegisterDatabaseBuilder

func RegisterDatabaseBuilder(typ string, b DatabaseBuilder) error

RegisterDatabaseBuilder registers a database builder for the given type string.

func RegisterLogBuilder

func RegisterLogBuilder(typ string, b LogBuilder) error

RegisterLogBuilder registers a log builder for the given type string.

func RegisterMetricsBuilder

func RegisterMetricsBuilder(typ string, b MetricsBuilder) error

RegisterMetricsBuilder registers a metrics builder for the given type string.

func RegisterRegistryAction

func RegisterRegistryAction(typ string, a RegistryAction) error

RegisterRegistryAction registers a registry action for the given type string.

func RegisterScriptEngineBuilder

func RegisterScriptEngineBuilder(typ string, b ScriptEngineBuilder) error

RegisterScriptEngineBuilder registers a script engine builder for the given type string.

func RegisterServerBuilder

func RegisterServerBuilder(typ string, b ServerBuilder) error

RegisterServerBuilder registers a server builder for the given type string.

func RegisterStorageBuilder

func RegisterStorageBuilder(typ string, b StorageBuilder) error

RegisterStorageBuilder registers a storage builder for the given type string.

func RegisterTracerBuilder

func RegisterTracerBuilder(typ string, b TracerBuilder) error

RegisterTracerBuilder registers a tracer builder for the given type string.

func RegisterWorkflowBuilder

func RegisterWorkflowBuilder(typ string, b WorkflowBuilder) error

RegisterWorkflowBuilder registers a workflow builder for the given type string.

func Run

func Run(ctx context.Context, cfg *v1.BootstrapConfig) error

Run is a convenience function that calls Bootstrap and then wind.App.Run. It is intended for simple use cases where broker instances are not needed; for more control, use Bootstrap or BootstrapWithContext directly.

func RunApp

func RunApp(configPath string) error

RunApp is the sealed one-call entry point. It:

  1. Creates a signal-aware context (SIGINT/SIGTERM)
  2. Loads config from the given file path
  3. Bootstraps the application
  4. Runs the app and cleans up on exit

This is the simplest way to start an application:

func main() {
    if err := bootstrap.RunApp("config.yaml"); err != nil {
        log.Fatal(err)
    }
}

func RunAppWithFlags

func RunAppWithFlags(flags *CommandFlags, opts ...func(root *cobra.Command)) error

RunAppWithFlags creates a cobra root command that loads config from the --conf flag and runs the application. It allows further customisation of the root command (adding sub-commands, extra flags, etc.).

Usage:

func main() {
    flags := bootstrap.NewCommandFlags()
    if err := bootstrap.RunAppWithFlags(flags); err != nil {
        os.Exit(1)
    }
}

Types

type AiBuilder

type AiBuilder func(ctx context.Context, cfg *v1.Ai) (any, func(), error)

AiBuilder builds an AI model client and returns it along with an optional cleanup function.

type BrokerBuilder

type BrokerBuilder func(ctx context.Context, cfg *v1.Broker) (any, func(), error)

BrokerBuilder builds a broker instance and returns it along with an optional cleanup function. The returned instance (any) is the concrete broker object that callers can use for Publish/Subscribe operations.

The type key (e.g. "kafka", "rabbitmq") is used to look up the instance via Context.Broker after bootstrap.

type CacheBuilder

type CacheBuilder func(ctx context.Context, cfg *v1.Cache) (any, func(), error)

CacheBuilder builds a cache instance and returns it along with an optional cleanup function.

type CommandFlags

type CommandFlags struct {
	// Conf is the path to the bootstrap config file.
	// Supported formats: .yaml, .yml, .json, .bin, .pb.
	Conf string
}

CommandFlags holds the CLI flags consumed by the bootstrap framework.

func NewCommandFlags

func NewCommandFlags() *CommandFlags

NewCommandFlags returns a CommandFlags with sensible defaults.

func (*CommandFlags) AddFlags

func (f *CommandFlags) AddFlags(cmd *cobra.Command)

AddFlags binds the flags to the given cobra command.

type ConfigAction

type ConfigAction func(ctx context.Context, cfg *v1.Config) (func(), error)

ConfigAction performs config source loading/watching.

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context holds the application lifecycle state created by Bootstrap or BootstrapWithContext.

It is safe to read fields from multiple goroutines after Bootstrap returns.

func BootstrapWithContext

func BootstrapWithContext(ctx context.Context, cfg *v1.BootstrapConfig) (*Context, error)

BootstrapWithContext is like Bootstrap but returns a *Context that wraps the app, config, broker instances, cleanup, and a cancellable context.

The caller should call ctx.Cleanup() after the app stops. Use ctx.Broker(name) to retrieve a specific broker instance.

func (*Context) Ai

func (c *Context) Ai(name string) any

Ai returns the AI model client instance for the given type name (e.g. AiTypeOpenAI, AiTypeLangChainGo, AiTypeEino). Returns nil if no AI client with that name was configured.

The caller should type-assert the result to the concrete client type:

client, ok := ctx.Ai(bootstrap.AiTypeOpenAI).(*openai.Client)
if ok { /* use client for chat completions */ }

func (*Context) Ais

func (c *Context) Ais() map[string]any

Ais returns all AI client instances as a map keyed by type name. Returns nil if no AI client was configured.

func (*Context) App

func (c *Context) App() *wind.App

App returns the underlying *wind.App.

func (*Context) Broker

func (c *Context) Broker(name string) any

Broker returns the broker instance for the given type name (e.g. BrokerTypeKafka, BrokerTypeRabbitMQ). Returns nil if no broker with that name was configured.

The caller should type-assert the result to the concrete broker type:

if b, ok := ctx.Broker(bootstrap.BrokerTypeKafka).(*kafka.Broker); ok {
    b.Publish(ctx, msg)
}

func (*Context) Brokers

func (c *Context) Brokers() map[string]any

Brokers returns all broker instances as a map keyed by type name. Returns nil if no broker was configured.

func (*Context) Cache

func (c *Context) Cache(name string) any

Cache returns the cache instance for the given type name (e.g. CacheTypeLocal, CacheTypeRedis). Returns nil if no cache with that name was configured.

The caller should type-assert the result to the concrete cache type:

c, ok := ctx.Cache(bootstrap.CacheTypeLocal).(*local.Cache)
if ok { /* use c for Get/Set operations */ }

func (*Context) Caches

func (c *Context) Caches() map[string]any

Caches returns all cache instances as a map keyed by type name. Returns nil if no cache was configured.

func (*Context) Cancel

func (c *Context) Cancel()

Cancel triggers graceful shutdown (idempotent).

func (*Context) Cleanup

func (c *Context) Cleanup()

Cleanup releases all resources. It is safe to call multiple times.

func (*Context) Config

func (c *Context) Config() *v1.BootstrapConfig

Config returns the loaded bootstrap configuration.

func (*Context) Database

func (c *Context) Database(name string) any

Database returns the database client instance for the given type name (e.g. DatabaseTypeGorm, DatabaseTypeMongodb). Returns nil if no database client with that name was configured.

func (*Context) Databases

func (c *Context) Databases() map[string]any

Databases returns all database client instances as a map keyed by type name. Returns nil if no database was configured.

func (*Context) ScriptEngine

func (c *Context) ScriptEngine(name string) any

ScriptEngine returns the script engine instance for the given type name (e.g. ScriptEngineLua, ScriptEngineJavaScript). Returns nil if no script engine with that name was configured.

The caller should type-assert the result to the concrete engine type:

eng, ok := ctx.ScriptEngine(bootstrap.ScriptEngineLua).(scriptEngine.Engine)
if ok { /* use eng for Eval/Execute */ }

func (*Context) ScriptEngines

func (c *Context) ScriptEngines() map[string]any

ScriptEngines returns all script engine instances as a map keyed by type name. Returns nil if no script engine was configured.

func (*Context) Storage

func (c *Context) Storage(name string) any

Storage returns the storage client instance for the given type name (e.g. StorageTypeMinio, StorageTypeS3). Returns nil if no storage with that name was configured.

The caller should type-assert the result to the concrete storage type:

s, ok := ctx.Storage(bootstrap.StorageTypeMinio).(*minioPlugin.Storage)
if ok { /* use s for PutObject/GetObject */ }

func (*Context) Storages

func (c *Context) Storages() map[string]any

Storages returns all storage instances as a map keyed by type name. Returns nil if no storage was configured.

func (*Context) Workflow

func (c *Context) Workflow(name string) any

Workflow returns the workflow engine client instance for the given type name (e.g. WorkflowTypeTemporal, WorkflowTypeArgo). Returns nil if no workflow client with that name was configured.

The caller should type-assert the result to the concrete client type:

wc, ok := ctx.Workflow(bootstrap.WorkflowTypeTemporal).(*temporal.WorkflowClient)
if ok { /* use wc for workflow operations */ }

func (*Context) Workflows

func (c *Context) Workflows() map[string]any

Workflows returns all workflow client instances as a map keyed by type name. Returns nil if no workflow client was configured.

type DatabaseBuilder

type DatabaseBuilder func(ctx context.Context, cfg *v1.Database) (any, func(), error)

DatabaseBuilder builds a database client instance and returns it along with an optional cleanup function.

type LogBuilder

type LogBuilder func(cfg *v1.Logger) (log.Logger, func(), error)

LogBuilder builds a log.Logger from a [Logger] config.

type MetricsBuilder

type MetricsBuilder func(cfg *v1.Metrics) (func(), error)

MetricsBuilder builds a metrics backend.

type RegistryAction

type RegistryAction func(ctx context.Context, appCfg *v1.App, endpoints []string, cfg *v1.Registry) (func(), error)

RegistryAction performs registration/deregistration lifecycle.

The cfg parameter carries the full registry configuration so that the action can extract its own sub-configuration. Deprecated: Use RegisterRegistryAction with the new signature instead.

type ScriptEngineBuilder

type ScriptEngineBuilder func(ctx context.Context, cfg *v1.Script) (any, func(), error)

ScriptEngineBuilder builds a script engine instance and returns it along with an optional cleanup function.

type ServerBuilder

type ServerBuilder func(cfg *v1.Server) (transport.Server, error)

ServerBuilder builds a transport.Server from a [Server] config.

type StorageBuilder

type StorageBuilder func(ctx context.Context, cfg *v1.Storage) (any, func(), error)

StorageBuilder builds a storage client instance and returns it along with an optional cleanup function. The returned instance (any) is the concrete storage client that callers can use for object operations.

The type key (e.g. "minio", "s3") is used to look up the instance via Context.Storage after bootstrap.

type TracerBuilder

type TracerBuilder func(cfg *v1.Tracer) (interface{}, func(), error)

TracerBuilder builds a tracer provider.

type WorkflowBuilder

type WorkflowBuilder func(ctx context.Context, cfg *v1.Workflow) (any, func(), error)

WorkflowBuilder builds a workflow engine client and returns it along with an optional cleanup function.

Directories

Path Synopsis
conf module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL