lynx

package module
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2026 License: Apache-2.0 Imports: 19 Imported by: 9

README

Lynx

Go Version License

Lynx 是一个轻量级的 Go 微服务框架,提供了开箱即用的应用生命周期管理、组件系统、HTTP 服务器、健康检查、配置管理和事件驱动等功能。

特性

  • 应用生命周期管理 - 简洁的启动/停止流程,支持优雅关闭
  • 组件系统 - 基于 Component 接口的插件化架构
  • HTTP 服务器 - 内置 HTTP 服务器,支持健康检查和请求日志
  • 健康检查 - 集成健康检查机制,便于监控和服务发现
  • 配置管理 - 基于 Viper 的灵活配置系统,支持多来源配置
  • 事件驱动 - 内置 PubSub 支持,轻松实现异步消息处理
  • Kafka 集成 - 提供 Kafka Binder,简化消息队列的使用
  • 定时任务 - 基于 Cron 的调度器支持
  • 日志集成 - 支持 slogzap 日志库
  • CLI 模式 - 支持命令行工具开发
  • 依赖注入 - 支持 Wire 依赖注入

安装

go get github.com/lynx-go/lynx

快速开始

HTTP 服务示例
package main

import (
    "context"
    "encoding/json"
    "net/http"

    "github.com/lynx-go/lynx"
    "github.com/lynx-go/lynx/server/http"
)

func main() {
    opts := lynx.NewOptions(
        lynx.WithName("my-app"),
        lynx.WithVersion("1.0.0"),
    )

    cli := lynx.New(opts, func(ctx context.Context, app lynx.Lynx) error {
        // 创建 HTTP 路由
        router := http.NewRouter()
        router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            json.NewEncoder(w).Encode(map[string]string{
                "hello": "world",
                "app":   lynx.NameFromContext(app.Context()),
            })
        })

        // 注册 HTTP 服务器组件
        return app.Hooks(lynx.Components(
            http.NewServer(router,
                http.WithAddr(":8080"),
                http.WithHealthCheck(app.HealthCheckFunc()),
            ),
        ))
    })

    cli.Run()
}

运行:

go run main.go --addr=:8080

访问 http://localhost:8080 查看结果,访问 http://localhost:8080/health 查看健康状态。

使用配置文件

创建 config.yaml

addr: ":8080"
log_level: "debug"

代码中绑定配置:

opts := lynx.NewOptions(
    lynx.WithSetFlagsFunc(func(f *pflag.FlagSet) {
        f.StringP("config", "c", "config.yaml", "config file path")
    }),
    lynx.WithBindConfigFunc(func(f *pflag.FlagSet, v *viper.Viper) error {
        if c, _ := f.GetString("config"); c != "" {
            v.SetConfigFile(c)
        }
        return nil
    }),
)
使用事件驱动
import "github.com/lynx-go/lynx/contrib/pubsub"

// 定义事件处理器
handler := pubsub.HandlerFunc(func(ctx context.Context, msg *message.Message) error {
    fmt.Printf("Received message: %s\n", msg.Payload)
    return nil
})

// 订阅主题
broker.Subscribe("user.created", "handler-1", handler)

// 发布消息
msg := pubsub.NewJSONMessage(map[string]string{"user": "alice"})
broker.Publish(ctx, "user.created", msg)
使用 Kafka Binder
import "github.com/lynx-go/lynx/contrib/kafka"

binder := kafka.NewBinder(kafka.BinderOptions{
    SubscribeOptions: map[string]kafka.ConsumerOptions{
        "user.created": {
            Brokers: []string{"localhost:9092"},
            GroupID: "my-group",
        },
    },
    PublishOptions: map[string]kafka.ProducerOptions{
        "user.created": {
            Brokers: []string{"localhost:9092"},
        },
    },
})

app.Hooks(lynx.ComponentBuilders(binder.ConsumerBuilders()...))
app.Hooks(lynx.Components(binder))
使用定时任务
import "github.com/lynx-go/lynx/contrib/schedule"

// 实现任务接口
type MyTask struct{}

func (t *MyTask) Name() string { return "my-task" }
func (t *MyTask) Cron() string { return "*/5 * * * *" } // 每5分钟执行
func (t *MyTask) HandlerFunc() schedule.HandlerFunc {
    return func(ctx context.Context) error {
        fmt.Println("Task executed!")
        return nil
    }
}

scheduler, _ := schedule.NewScheduler([]schedule.Task{&MyTask{}})
app.Hooks(lynx.Components(scheduler))

核心概念

Component(组件)

所有可管理的功能单元都实现 Component 接口:

type Component interface {
    Name() string
    Init(app Lynx) error
    Start(ctx context.Context) error
    Stop(ctx context.Context)
}
Hooks(钩子)

支持在应用启动和停止时执行自定义逻辑:

app.Hooks(
    lynx.OnStart(func(ctx context.Context) error {
        // 启动时执行
        return nil
    }),
    lynx.OnStop(func(ctx context.Context) error {
        // 停止时执行
        return nil
    }),
)
依赖注入

结合 Wire 使用:

//go:generate wire
func InitializeApp() (*Bootstrap, error) {
    wire.Build(
        NewServer,
        NewDatabase,
        NewRepository,
        NewService,
        NewBootstrap,
    )
    return &Bootstrap{}, nil
}

项目结构

lynx/
├── boot/           # 应用引导和依赖注入
├── cli/            # CLI 模式支持
├── command/        # 命令行命令
├── component.go    # 组件接口定义
├── contrib/        # 扩展组件
│   ├── kafka/      # Kafka 支持
│   ├── pubsub/     # 消息发布订阅
│   ├── schedule/   # 定时任务
│   └── zap/        # Zap 日志集成
├── hooks.go        # Hooks 机制
├── options.go      # 配置选项
├── pkg/            # 内部工具包
├── server/         # 服务器实现
│   └── http/       # HTTP 服务器
└── _examples/      # 示例代码
    ├── boot/       # 依赖注入示例
    ├── cli/        # CLI 示例
    ├── http/       # HTTP 服务示例
    ├── pubsub/     # 消息队列示例
    └── schedule/   # 定时任务示例

配置

Lynx 使用 Viper 进行配置管理,支持多种配置来源:

  • 命令行参数
  • 环境变量
  • 配置文件(JSON/YAML/TOML)
  • 远程配置中心

默认支持的命令行参数:

-c, --config string      配置文件路径
--config-type string     配置文件类型 (默认 "yaml")
--config-dir string      配置文件目录
--log-level string       日志级别 (默认 "info")

扩展模块

Contrib 模块

Lynx 提供了多个可选的扩展模块:

# HTTP 服务器
github.com/lynx-go/lynx/server/http

# Kafka 支持
github.com/lynx-go/lynx/contrib/kafka

# PubSub 抽象
github.com/lynx-go/lynx/contrib/pubsub

# 定时任务
github.com/lynx-go/lynx/contrib/schedule

# Zap 日志
github.com/lynx-go/lynx/contrib/zap

依赖要求

  • Go 1.24.2 或更高版本

License

Apache License 2.0

贡献

欢迎提交 Issue 和 Pull Request!

相关链接

Documentation

Index

Constants

View Source
const (
	DefaultName            = "lynx-app"
	DefaultShutdownTimeout = 5 * time.Second
	MinCloseTimeout        = 1 * time.Second
	MaxCloseTimeout        = 5 * time.Minute
)

Default values for Options.

Variables

View Source
var (
	ErrNotInitialized  = errorf("component not initialized")
	ErrConfigNotFound  = errorf("config not found")
	ErrComponentFailed = errorf("component failed")
)

Common errors that can be used throughout the framework.

View Source
var (
	ErrNameTooLong          = errors.New("name must be at most 63 characters")
	ErrCloseTimeoutTooSmall = errors.New("close timeout must be at least 1 second")
	ErrCloseTimeoutTooLarge = errors.New("close timeout must be at most 5 minutes")
)

Validation errors for Options.

Functions

func DefaultBindConfigFunc added in v0.6.0

func DefaultBindConfigFunc(f *pflag.FlagSet, v *viper.Viper) error

func DefaultSetFlagsFunc added in v0.6.0

func DefaultSetFlagsFunc(f *pflag.FlagSet)

func IDFromContext added in v0.6.0

func IDFromContext(ctx context.Context) string

IDFromContext returns the instance ID from the context. Returns an empty string if the ID is not set or has wrong type.

func NameFromContext added in v0.6.0

func NameFromContext(ctx context.Context) string

NameFromContext returns the application name from the context. Returns an empty string if the name is not set or has wrong type.

func TagNameJSON added in v0.6.0

func TagNameJSON(config *mapstructure.DecoderConfig)

func TagNameYAML added in v0.7.2

func TagNameYAML(config *mapstructure.DecoderConfig)

func VersionFromContext added in v0.6.0

func VersionFromContext(ctx context.Context) string

VersionFromContext returns the application version from the context. Returns an empty string if the version is not set or has wrong type.

Types

type BindConfigFunc added in v0.6.0

type BindConfigFunc func(f *pflag.FlagSet, v *viper.Viper) error

type BuildOptions added in v0.6.0

type BuildOptions struct {
	Instances int `json:"instances"` // 实例数
}

type CLI added in v0.0.4

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

func New

func New(o *Options, setup SetupFunc) *CLI

func (*CLI) Run added in v0.0.4

func (app *CLI) Run()

func (*CLI) RunE added in v0.6.0

func (app *CLI) RunE() error

type CommandFunc added in v0.6.0

type CommandFunc func(ctx context.Context) error

type CommandOption added in v0.0.6

type CommandOption func(*CommandOptions)

CommandOption is a function that configures CommandOptions.

func WithBackoff added in v0.7.1

func WithBackoff(initial, max time.Duration) CommandOption

WithBackoff sets the initial and maximum backoff durations.

func WithMaxTries added in v0.7.1

func WithMaxTries(n uint) CommandOption

WithMaxTries sets the maximum number of retry attempts.

type CommandOptions added in v0.7.1

type CommandOptions struct {
	MaxTries       uint
	InitialBackoff time.Duration
	MaxBackoff     time.Duration
}

CommandOptions configures the command component behavior.

type Component added in v0.6.0

type Component interface {
	Name() string
	LifecycleManaged
}

func NewCommand added in v0.6.0

func NewCommand(fn CommandFunc, opts ...CommandOption) Component

NewCommand creates a new command component with the given function and options.

type ComponentBuilder added in v0.6.0

type ComponentBuilder interface {
	Build() Component
	Options() BuildOptions
}

type ComponentBuilderSet added in v0.6.0

type ComponentBuilderSet []ComponentBuilder

type ComponentBuilderSetFunc added in v0.6.0

type ComponentBuilderSetFunc func() ComponentBuilderSet

type ComponentSet added in v0.6.0

type ComponentSet []Component

type HealthCheckFunc added in v0.6.0

type HealthCheckFunc func() []health.Checker

type HealthChecker added in v0.6.0

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

func (*HealthChecker) CheckHealth added in v0.6.0

func (check *HealthChecker) CheckHealth() error

func (*HealthChecker) SetHealthy added in v0.6.0

func (check *HealthChecker) SetHealthy(healthy bool)

type HookFunc added in v0.6.0

type HookFunc func(ctx context.Context) error

type HookOption added in v0.6.0

type HookOption func(*hookOptions)

func ComponentBuilders added in v0.6.0

func ComponentBuilders(builders ...ComponentBuilder) HookOption

func Components added in v0.6.0

func Components(components ...Component) HookOption

func OnStart added in v0.6.0

func OnStart(fns ...HookFunc) HookOption

func OnStop added in v0.6.0

func OnStop(fns ...HookFunc) HookOption

type Hooks

type Hooks interface {
	OnStart(fns ...HookFunc)
	OnStop(fns ...HookFunc)
}

type LifecycleManaged added in v0.6.0

type LifecycleManaged interface {
	Init(app Lynx) error
	Start(ctx context.Context) error
	Stop(ctx context.Context)
}

type Lynx added in v0.6.0

type Lynx interface {
	// Close 关闭应用实例
	Close()
	// Config 获取配置实例
	Config() *viper.Viper
	// Context 获取应用上下文
	Context() context.Context
	// CLI 注册启动的命令,用于 CLI 模式
	CLI(cmd CommandFunc) error
	// Hooks 添加 OnStart/OnStop/Component/ComponentBuilder Hooks
	Hooks(hooks ...HookOption) error

	// HealthCheckFunc 注册到 HTTP 的 Health Check 方法
	HealthCheckFunc() HealthCheckFunc
	// Run 启用 CLI
	Run() error
	// SetLogger 设置 logger
	SetLogger(logger *slog.Logger)
	// Logger 获取 logger
	Logger(kwargs ...any) *slog.Logger
}

type OnStartHooks added in v0.6.0

type OnStartHooks []HookFunc

type OnStopHooks added in v0.6.0

type OnStopHooks []HookFunc

type Option

type Option func(*Options)

func WithBindConfigFunc added in v0.6.0

func WithBindConfigFunc(f BindConfigFunc) Option

func WithExitSignals added in v0.6.0

func WithExitSignals(signals ...os.Signal) Option

func WithID

func WithID(id string) Option

func WithName

func WithName(name string) Option

func WithSetFlagsFunc added in v0.6.0

func WithSetFlagsFunc(f SetFlagsFunc) Option

func WithShutdownTimeout added in v0.7.2

func WithShutdownTimeout(timeout time.Duration) Option

func WithUseDefaultConfigFlagsFunc added in v0.6.0

func WithUseDefaultConfigFlagsFunc() Option

func WithVersion

func WithVersion(v string) Option

type Options added in v0.6.0

type Options struct {
	ID              string         `json:"id"`
	Name            string         `json:"name"`
	Version         string         `json:"version"`
	SetFlagsFunc    SetFlagsFunc   `json:"-"`
	BindConfigFunc  BindConfigFunc `json:"-"`
	ExitSignals     []os.Signal    `json:"-"`
	ShutdownTimeout time.Duration  `json:"shutdown_timeout"`
}

func NewOptions added in v0.6.0

func NewOptions(opts ...Option) *Options

func (*Options) EnsureDefaults added in v0.6.0

func (o *Options) EnsureDefaults()

EnsureDefaults sets default values for unset fields and validates the options.

func (*Options) String added in v0.6.0

func (o *Options) String() string

func (*Options) Validate added in v0.7.1

func (o *Options) Validate() error

Validate checks if the Options values are valid.

type ServerLike added in v0.6.0

type ServerLike interface {
	health.Checker
	Component
}

type SetFlagsFunc added in v0.6.0

type SetFlagsFunc func(f *pflag.FlagSet)

type SetupFunc added in v0.0.4

type SetupFunc func(ctx context.Context, app Lynx) error

type ShutdownErrors added in v0.7.1

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

ShutdownErrors collects errors that occur during shutdown. It is safe for concurrent use.

func (*ShutdownErrors) Add added in v0.7.1

func (e *ShutdownErrors) Add(err error)

Add appends an error to the collection. Nil errors are ignored.

func (*ShutdownErrors) Error added in v0.7.1

func (e *ShutdownErrors) Error() string

Error returns a semicolon-separated string of all collected errors.

func (*ShutdownErrors) Errors added in v0.7.1

func (e *ShutdownErrors) Errors() []error

Errors returns a copy of all collected errors.

func (*ShutdownErrors) HasErrors added in v0.7.1

func (e *ShutdownErrors) HasErrors() bool

HasErrors returns true if any errors have been collected.

Directories

Path Synopsis
contrib
kafka module
log/zap module
pubsub module
schedule module
zap module
pkg
server

Jump to

Keyboard shortcuts

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