config

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2026 License: Apache-2.0 Imports: 8 Imported by: 9 modules, 9 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

framework-config

Go framework package for config.

Installation

go get github.com/go-anyway/framework-config@v1.0.0

Usage

See documentation for usage examples.

License

Apache License 2.0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultConfigFiles = map[string]string{
	"mysql":         "mysql.yaml",
	"redis":         "redis.yaml",
	"message_queue": "message_queue.yaml",
	"clickhouse":    "clickhouse.yaml",
	"email":         "email.yaml",
	"server":        "server.yaml",
	"log":           "log.yaml",
	"xxl_job":       "xxljob.yaml",
	"elasticsearch": "elasticsearch.yaml",
	"mongodb":       "mongodb.yaml",
	"postgresql":    "postgresql.yaml",
	"oss":           "oss.yaml",
	"config_center": "config_center.yaml",
	"services":      "services.yaml",
}

DefaultConfigFiles 默认配置文件映射 这是统一的配置映射关系,所有服务都使用这个映射 如果某个服务不需要某个配置,对应的配置文件不存在时会自动跳过 配置模块名对应 ConfigRegistry 中的字段名(yaml tag)

Functions

func ApplyDefaults

func ApplyDefaults(cfg interface{})

ApplyDefaults 应用默认值到结构体

func ExpandEnvVars

func ExpandEnvVars(data []byte) []byte

ExpandEnvVars 展开环境变量引用,支持 ${VAR:-default} 格式

func IsEmpty

func IsEmpty(v reflect.Value) bool

IsEmpty 检查值是否为空(通用工具函数)

func LoadFromFiles

func LoadFromFiles(configDir string, configFiles map[string]string, target interface{}) error

LoadFromFiles 从配置文件加载配置到目标结构 configDir: 配置目录路径 configFiles: 配置文件名映射,key 为配置模块名,value 为文件名 target: 目标配置结构,必须是指向结构体的指针

func SetFieldByPath

func SetFieldByPath(target interface{}, fieldPath, value string) error

SetFieldByPath 根据路径设置字段值

func Validate

func Validate(cfg interface{}) error

Validate 验证配置结构体 注意:必填字段验证已移至 app.ValidateConfig,此函数保留用于未来扩展通用验证逻辑

Types

type CORSConfig

type CORSConfig struct {
	Enabled        bool        `yaml:"enabled" env:"CORS_ENABLED" default:"true"`
	AllowedOrigins StringSlice `yaml:"allowed_origins" env:"CORS_ORIGINS"` // 空表示允许所有,支持数组或逗号分隔字符串
	AllowedMethods StringSlice `yaml:"allowed_methods" env:"CORS_METHODS" default:"GET,POST,PUT,DELETE,PATCH,OPTIONS"`
	AllowedHeaders StringSlice `` /* 153-byte string literal not displayed */
	MaxAge         Duration    `yaml:"max_age" env:"CORS_MAX_AGE" default:"12h"`
}

CORSConfig CORS 配置

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	Enabled     bool     `yaml:"enabled" env:"CIRCUIT_BREAKER_ENABLED" default:"false"`
	MaxRequests uint32   `yaml:"max_requests" env:"CIRCUIT_BREAKER_MAX_REQUESTS" default:"3"`
	Interval    Duration `yaml:"interval" env:"CIRCUIT_BREAKER_INTERVAL" default:"60s"`
	Timeout     Duration `yaml:"timeout" env:"CIRCUIT_BREAKER_TIMEOUT" default:"30s"`
}

CircuitBreakerConfig 熔断器配置

type Duration

type Duration time.Duration

Duration 是 time.Duration 的别名,用于 YAML 解析

func (*Duration) Duration

func (d *Duration) Duration() time.Duration

Duration 返回 time.Duration

func (*Duration) UnmarshalYAML

func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML 实现 yaml.Unmarshaler 接口

type FeaturesConfig

type FeaturesConfig struct {
	Metrics        MetricsConfig        `yaml:"metrics"`
	RateLimit      RateLimitConfig      `yaml:"rate_limit"`
	Tracing        TracingConfig        `yaml:"tracing"`
	CORS           CORSConfig           `yaml:"cors"`
	Timeout        TimeoutConfig        `yaml:"timeout"`
	SizeLimit      SizeLimitConfig      `yaml:"size_limit"`
	JWT            JWTConfig            `yaml:"jwt"`
	CircuitBreaker CircuitBreakerConfig `yaml:"circuit_breaker"`
}

FeaturesConfig 功能特性配置(用于 Gateway)

type JWTConfig

type JWTConfig struct {
	Enabled    bool     `yaml:"enabled" env:"JWT_ENABLED" default:"false"`
	SecretKey  string   `yaml:"secret_key" env:"JWT_SECRET_KEY"` // 当 enabled=true 时必填
	Expiration Duration `yaml:"expiration" env:"JWT_EXPIRATION" default:"24h"`
	Issuer     string   `yaml:"issuer" env:"JWT_ISSUER" default:"ai-api-market"`
}

JWTConfig JWT 认证配置

type LoadResult

type LoadResult struct {
	Registry interface{} // 配置注册表(通常是 *shared.ConfigRegistry)
}

LoadResult 配置加载结果

func LoadConfig

func LoadConfig(configDir, envPrefix string, flags []string, registry interface{}, setField SetFieldFunc, configFiles map[string]string) (*LoadResult, error)

LoadConfig 统一配置加载函数 自动检测配置中心并创建实例,整合所有配置加载逻辑 configDir: 配置目录路径 envPrefix: 环境变量前缀 flags: 命令行参数 registry: 配置注册表(必须是指向结构体的指针) setField: 字段设置函数,用于将配置值设置到 registry 上 configFiles: 配置文件映射(如果为 nil,使用 DefaultConfigFiles)

type LoaderConfig

type LoaderConfig struct {
	ConfigDir string
	EnvPrefix string
	Flags     []string
}

LoaderConfig 配置加载器配置

type LoaderOption

type LoaderOption func(*LoaderConfig)

LoaderOption 配置加载器选项

func WithConfigDir

func WithConfigDir(dir string) LoaderOption

WithConfigDir 设置配置目录

func WithEnvPrefix

func WithEnvPrefix(prefix string) LoaderOption

WithEnvPrefix 设置环境变量前缀

func WithFlags

func WithFlags(flags []string) LoaderOption

WithFlags 设置命令行参数

type MessageQueueConfig

type MessageQueueConfig struct {
	// Type 消息队列类型
	Type MessageQueueType `yaml:"type" env:"MESSAGE_QUEUE_TYPE" default:"none"`
	// Kafka Kafka 配置(当 type=kafka 时)
	// 使用 interface{} 避免循环依赖,实际类型为 *messagequeue.KafkaConfig
	Kafka interface{} `yaml:"kafka,omitempty"`
	// RabbitMQ RabbitMQ 配置(当 type=rabbitmq 时)
	// 使用 interface{} 避免循环依赖,实际类型为 *messagequeue.RabbitMQConfig
	RabbitMQ interface{} `yaml:"rabbitmq,omitempty"`
}

MessageQueueConfig 统一的消息队列配置 用于统一管理不同消息队列的配置 注意:为了避免循环依赖,使用 interface{} 类型 实际类型为:

  • Kafka: *messagequeue.KafkaConfig
  • RabbitMQ: *messagequeue.RabbitMQConfig

type MessageQueueType

type MessageQueueType string

MessageQueueType 消息队列类型

const (
	// MessageQueueTypeNone 不使用消息队列
	MessageQueueTypeNone MessageQueueType = "none"
	// MessageQueueTypeKafka Kafka 消息队列
	MessageQueueTypeKafka MessageQueueType = "kafka"
	// MessageQueueTypeRabbitMQ RabbitMQ 消息队列
	MessageQueueTypeRabbitMQ MessageQueueType = "rabbitmq"
)

func (MessageQueueType) IsValid

func (t MessageQueueType) IsValid() bool

IsValid 检查消息队列类型是否有效

func (MessageQueueType) String

func (t MessageQueueType) String() string

String 返回消息队列类型的字符串表示

type MetricsConfig

type MetricsConfig struct {
	Enabled bool `yaml:"enabled" env:"METRICS_ENABLED" default:"true"`
}

MetricsConfig Metrics 监控配置

type RateLimitConfig

type RateLimitConfig struct {
	Enabled bool    `yaml:"enabled" env:"RATE_LIMIT_ENABLED" default:"true"`
	Rate    float64 `yaml:"rate" env:"RATE_LIMIT_RATE" default:"10"`          // 每秒请求数
	Burst   int     `yaml:"burst" env:"RATE_LIMIT_BURST" default:"20"`        // 突发请求数
	Storage string  `yaml:"storage" env:"RATE_LIMIT_STORAGE" default:"local"` // 存储类型:local(本地)或 redis(分布式)
}

RateLimitConfig 限流配置

type ServerFeaturesConfig

type ServerFeaturesConfig struct {
	Metrics        MetricsConfig        `yaml:"metrics"`
	Tracing        TracingConfig        `yaml:"tracing"`
	CircuitBreaker CircuitBreakerConfig `yaml:"circuit_breaker"`
}

ServerFeaturesConfig 服务端功能特性配置(用于 RPC 服务)

type SetFieldFunc

type SetFieldFunc func(module, fieldPath, value string) error

SetFieldFunc 字段设置函数类型 用于服务特定的字段设置逻辑

type SizeLimitConfig

type SizeLimitConfig struct {
	Enabled    bool   `yaml:"enabled" env:"SIZE_LIMIT_ENABLED" default:"true"`
	MaxSize    int64  `yaml:"max_size" env:"REQUEST_MAX_SIZE" default:"10485760"`     // 默认 10MB (10 * 1024 * 1024)
	MaxSizeStr string `yaml:"max_size_str" env:"REQUEST_MAX_SIZE_STR" default:"10MB"` // 人类可读格式,如 "10MB", "1GB"
}

SizeLimitConfig 请求体大小限制配置

type StringSlice

type StringSlice []string

StringSlice 支持从字符串(逗号分隔)或数组解析的字符串切片类型

func (*StringSlice) MarshalYAML

func (s *StringSlice) MarshalYAML() (interface{}, error)

MarshalYAML 实现 yaml.Marshaler 接口

func (*StringSlice) Strings

func (s *StringSlice) Strings() []string

Strings 返回字符串切片

func (*StringSlice) UnmarshalYAML

func (s *StringSlice) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML 实现 yaml.Unmarshaler 接口 支持两种格式: 1. 字符串(逗号分隔):"GET,POST,PUT" 2. 数组:["GET", "POST", "PUT"]

type TimeoutConfig

type TimeoutConfig struct {
	Enabled bool     `yaml:"enabled" env:"TIMEOUT_ENABLED" default:"true"`
	Timeout Duration `yaml:"timeout" env:"REQUEST_TIMEOUT" default:"30s"`
}

TimeoutConfig 超时配置

type TracingConfig

type TracingConfig struct {
	Enabled        bool    `yaml:"enabled" env:"TRACING_ENABLED" default:"false"`
	ServiceName    string  `yaml:"service_name" env:"TRACING_SERVICE_NAME" default:"ai-api-market"`
	ServiceVersion string  `yaml:"service_version" env:"TRACING_SERVICE_VERSION" default:"1.0.0"`
	Environment    string  `yaml:"environment" env:"TRACING_ENVIRONMENT" default:"development"`
	OTLEndpoint    string  `yaml:"otlp_endpoint" env:"OTLP_ENDPOINT" default:"http://localhost:4318/v1/traces"` // OTLP HTTP endpoint (Jaeger 从 v1.35.0 开始支持)
	SampleRate     float64 `yaml:"sample_rate" env:"TRACING_SAMPLE_RATE" default:"1.0"`                         // 采样率 0.0-1.0
}

TracingConfig 追踪配置

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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