config

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DriverMySQL    = "mysql"
	DriverPostgres = "postgres"
)

数据库驱动常量

Variables

View Source
var (
	ErrConfigNotLoaded = fmt.Errorf("配置未加载")
)

配置错误

Functions

func GetBool

func GetBool(key string) bool

GetBool 获取布尔配置

func GetInt

func GetInt(key string) int

GetInt 获取整数配置

func GetString

func GetString(key string) string

GetString 获取字符串配置

func GetStringMap

func GetStringMap(key string) map[string]any

GetStringMap 获取字符串映射配置

func GetViper

func GetViper() *viper.Viper

GetViper 获取 viper 实例(用于扩展配置)

func RegisterCallback

func RegisterCallback(cb func(*Config))

RegisterCallback 注册配置变更回调

func RegisterDSNBuilder

func RegisterDSNBuilder(name string, builder DSNBuilder, aliases ...string)

RegisterDSNBuilder 为指定驱动注册 DSN 构建器(驱动名大小写不敏感)。 aliases 用于注册同一驱动的别名,例如 postgres 的 "postgresql"、"pg"。 通常由 database 包通过 database.RegisterDialect 间接调用, 应用代码也可直接使用以扩展自定义驱动。

func RegisteredDrivers

func RegisteredDrivers() []string

RegisteredDrivers 返回所有已注册 DSN 构建器的驱动名(用于诊断)

func Reload

func Reload() error

Reload 重新加载配置文件

func Set

func Set(cfg *Config)

Set 手动设置配置(用于测试或动态修改)

func SetDefaultManager

func SetDefaultManager(m *Manager)

SetDefaultManager 替换全局默认配置管理器。 主要供应用层(如 App)在持有自己的 Manager 时使用, 使 config.Get / config.GetString 等便捷函数仍然能取到正确的配置。 传入 nil 表示重置为空管理器。

func StartWatcher

func StartWatcher() error

StartWatcher 启动配置文件监听

func StopWatcher

func StopWatcher()

StopWatcher 停止配置文件监听

Types

type AppConfig

type AppConfig struct {
	Name     string `mapstructure:"name"`      // 应用名称,如 "用户管理系统"
	SiteName string `mapstructure:"site_name"` // 站点别名,如 "site_a"、"user_api"
	Version  string `mapstructure:"version"`   // 应用版本
	Env      string `mapstructure:"env"`       // 运行环境: dev/test/prod
	Debug    bool   `mapstructure:"debug"`     // 是否开启调试模式
	BaseURL  string `mapstructure:"base_url"`  // 应用基础URL
}

AppConfig 应用配置 使用场景:

  • 缓存键名前缀: cache:{site_name}:user:1
  • 日志标识: [site_a] 2024-01-01 10:00:00 ...
  • 站点追踪: Request-ID 带站点标识
  • 分布式锁: lock:{site_name}:order:123

func (*AppConfig) GetCachePrefix

func (c *AppConfig) GetCachePrefix() string

GetCachePrefix 获取缓存键名前缀

func (*AppConfig) GetSiteName

func (c *AppConfig) GetSiteName() string

GetSiteName 获取站点别名,如果未设置则返回空字符串

func (*AppConfig) IsDebug

func (c *AppConfig) IsDebug() bool

IsDebug 是否调试模式

func (*AppConfig) IsDev

func (c *AppConfig) IsDev() bool

IsDev 是否开发环境

func (*AppConfig) IsProd

func (c *AppConfig) IsProd() bool

IsProd 是否生产环境

type CORSConfig

type CORSConfig struct {
	AllowedOrigins   []string `mapstructure:"allowed_origins"`   // 允许的域名列表
	AllowedMethods   []string `mapstructure:"allowed_methods"`   // 允许的方法
	AllowedHeaders   []string `mapstructure:"allowed_headers"`   // 允许的请求头
	ExposedHeaders   []string `mapstructure:"exposed_headers"`   // 暴露的响应头
	AllowCredentials bool     `mapstructure:"allow_credentials"` // 是否允许携带凭证
	MaxAge           int      `mapstructure:"max_age"`           // 预检请求缓存时间(秒)
}

CORSConfig CORS 跨域配置

func (*CORSConfig) GetAllowedHeaders

func (c *CORSConfig) GetAllowedHeaders() []string

GetAllowedHeaders 获取允许的请求头列表

func (*CORSConfig) GetAllowedMethods

func (c *CORSConfig) GetAllowedMethods() []string

GetAllowedMethods 获取允许的方法列表

func (*CORSConfig) GetAllowedOrigins

func (c *CORSConfig) GetAllowedOrigins() []string

GetAllowedOrigins 获取允许的域名列表

func (*CORSConfig) GetExposedHeaders

func (c *CORSConfig) GetExposedHeaders() []string

GetExposedHeaders 获取暴露的响应头列表

func (*CORSConfig) GetMaxAge

func (c *CORSConfig) GetMaxAge() int

GetMaxAge 获取预检请求缓存时间

type Config

type Config struct {
	App      AppConfig      `mapstructure:"app"`
	Server   ServerConfig   `mapstructure:"server"`
	Database DatabaseConfig `mapstructure:"database"`
	Redis    RedisConfig    `mapstructure:"redis"`
	JWT      JWTConfig      `mapstructure:"jwt"`
	SMS      SMSConfig      `mapstructure:"sms"`
	Storage  StorageConfig  `mapstructure:"storage"`
	Upload   UploadConfig   `mapstructure:"upload"`
	Log      LogConfig      `mapstructure:"log"`
	CORS     CORSConfig     `mapstructure:"cors"`
}

Config 全局配置结构体

func Get

func Get() *Config

Get 获取全局配置

func Load

func Load(configPath string) (*Config, error)

Load 加载配置文件

func LoadWithWatch

func LoadWithWatch(configPath string, onChange func(*Config)) (*Config, error)

LoadWithWatch 加载配置文件并启用热更新

func (*Config) GetAppName

func (c *Config) GetAppName() string

GetAppName 获取应用名称

func (*Config) GetSiteName

func (c *Config) GetSiteName() string

GetSiteName 获取站点别名

func (*Config) IsDevelopment

func (c *Config) IsDevelopment() bool

IsDevelopment 是否开发环境

func (*Config) IsProduction

func (c *Config) IsProduction() bool

IsProduction 是否生产环境

func (*Config) Validate added in v1.1.0

func (c *Config) Validate() error

Validate 校验配置完整性与取值合法性(#16)。 在 Manager.Load 解析后自动调用,把"运行时第一次请求才暴露"的配置错误 提前到进程启动期。返回的 error 描述具体字段,便于定位。

type DSNBuilder

type DSNBuilder func(*DatabaseConfig) string

DSNBuilder 根据 DatabaseConfig 生成连接字符串

func LookupDSNBuilder

func LookupDSNBuilder(name string) (DSNBuilder, bool)

LookupDSNBuilder 查找已注册的 DSN 构建器

type DatabaseConfig

type DatabaseConfig struct {
	// Driver 数据库驱动,支持 mysql(默认)与 postgres
	Driver string `mapstructure:"driver"`
	// Host 数据库主机
	Host string `mapstructure:"host"`
	// Port 数据库端口
	Port int `mapstructure:"port"`
	// User 数据库用户名
	User string `mapstructure:"user"`
	// Password 数据库密码
	Password string `mapstructure:"password"`
	// Name 数据库名
	Name string `mapstructure:"name"`
	// CustomDSN 自定义连接字符串,设置后优先于由 Host/Port 等字段生成的 DSN
	CustomDSN string `mapstructure:"dsn"`
	// MaxIdleConns 最大空闲连接数
	MaxIdleConns int `mapstructure:"max_idle_conns"`
	// MaxOpenConns 最大打开连接数
	MaxOpenConns int `mapstructure:"max_open_conns"`
	// ConnMaxIdleTime 连接最大空闲时间,如 "5m"(#21)。0 表示用驱动默认
	ConnMaxIdleTime time.Duration `mapstructure:"conn_max_idle_time"`
	// HealthCheckInterval 主库探活间隔,如 "30s"(#21)。0 表示用默认 30s
	HealthCheckInterval time.Duration `mapstructure:"health_check_interval"`
	// HealthCheckFailureThreshold 连续探活失败多少次标记不健康(#21)。0 表示用默认 3
	HealthCheckFailureThreshold int `mapstructure:"health_check_failure_threshold"`
}

DatabaseConfig 数据库配置

func (*DatabaseConfig) DSN

func (c *DatabaseConfig) DSN() string

DSN 根据驱动返回连接字符串。设置了 CustomDSN 时优先返回 CustomDSN; 未指定 Driver 时按 MySQL 处理(向后兼容)。 若驱动通过 RegisterDSNBuilder 注册过自定义构建器,则使用注册的构建器。

func (*DatabaseConfig) MySQLDSN

func (c *DatabaseConfig) MySQLDSN() string

MySQLDSN 返回 MySQL 连接字符串

func (*DatabaseConfig) PostgresDSN

func (c *DatabaseConfig) PostgresDSN() string

PostgresDSN 返回 PostgreSQL 连接字符串

type JWTConfig

type JWTConfig struct {
	Secret        string        `mapstructure:"secret"`
	Expire        time.Duration `mapstructure:"expire"`         // 过期时间,如 "24h"(time.Duration)
	RefreshExpire time.Duration `mapstructure:"refresh_expire"` // 刷新 token 过期时间,如 "168h"
	Issuer        string        `mapstructure:"issuer"`         // 签发者
	Algorithm     string        `mapstructure:"algorithm"`      // 签名算法:HS256(默认)/RS256
}

JWTConfig JWT 配置

type LocalStorageConfig

type LocalStorageConfig struct {
	Path    string `mapstructure:"path"`
	BaseURL string `mapstructure:"base_url"`
}

LocalStorageConfig 本地存储配置

type LogConfig

type LogConfig struct {
	Dir        string `mapstructure:"dir"`
	MaxSize    int    `mapstructure:"max_size"` // MB
	MaxBackups int    `mapstructure:"max_backups"`
	MaxAge     int    `mapstructure:"max_age"` // 天
	Compress   bool   `mapstructure:"compress"`
}

LogConfig 日志配置

type Manager

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

Manager 配置管理器

func NewManager

func NewManager(configPath string) *Manager

NewManager 创建配置管理器

func (*Manager) Get

func (m *Manager) Get() *Config

Get 获取配置

func (*Manager) GetViper

func (m *Manager) GetViper() *viper.Viper

GetViper 获取 viper 实例

func (*Manager) Load

func (m *Manager) Load() (*Config, error)

Load 加载配置文件

func (*Manager) LoadWithWatch

func (m *Manager) LoadWithWatch(onChange func(*Config)) (*Config, error)

LoadWithWatch 加载配置文件并启用热更新

func (*Manager) RegisterCallback

func (m *Manager) RegisterCallback(cb func(*Config))

RegisterCallback 注册配置变更回调

func (*Manager) Reload

func (m *Manager) Reload() error

Reload 重新加载配置文件

func (*Manager) Set

func (m *Manager) Set(cfg *Config)

Set 手动设置配置

func (*Manager) StartWatcher

func (m *Manager) StartWatcher() error

StartWatcher 启动配置文件监听

func (*Manager) StopWatcher

func (m *Manager) StopWatcher()

StopWatcher 停止配置文件监听

type OSSStorageConfig

type OSSStorageConfig struct {
	Endpoint        string `mapstructure:"endpoint"`
	Bucket          string `mapstructure:"bucket"`
	AccessKeyID     string `mapstructure:"access_key_id"`
	AccessKeySecret string `mapstructure:"access_key_secret"`
	BaseURL         string `mapstructure:"base_url"`
}

OSSStorageConfig OSS 存储配置

type RedisConfig

type RedisConfig struct {
	Host     string `mapstructure:"host"`
	Port     int    `mapstructure:"port"`
	Password string `mapstructure:"password"`
	DB       int    `mapstructure:"db"`
}

RedisConfig Redis 配置

func (*RedisConfig) Addr

func (c *RedisConfig) Addr() string

Addr 返回 Redis 地址

type SMSConfig

type SMSConfig struct {
	Enabled         bool   `mapstructure:"enabled"`
	Provider        string `mapstructure:"provider"`
	AccessKeyID     string `mapstructure:"access_key_id"`
	AccessKeySecret string `mapstructure:"access_key_secret"`
	SignName        string `mapstructure:"sign_name"`
	TemplateCode    string `mapstructure:"template_code"`
}

SMSConfig 短信配置

type ServerConfig

type ServerConfig struct {
	Host            string        `mapstructure:"host"` // 绑定地址,空=监听所有接口(0.0.0.0);"127.0.0.1"=仅本机;内网IP=绑定指定网卡
	Port            int           `mapstructure:"port"`
	Mode            string        `mapstructure:"mode"`             // development 或 production
	ReadTimeout     time.Duration `mapstructure:"read_timeout"`     // 读超时,如 "15s"
	WriteTimeout    time.Duration `mapstructure:"write_timeout"`    // 写超时,如 "30s"
	IdleTimeout     time.Duration `mapstructure:"idle_timeout"`     // 空闲超时,如 "60s"
	ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout"` // 优雅关闭超时,如 "30s"
	MaxHeaderBytes  int           `mapstructure:"max_header_bytes"` // 最大请求头字节数
	TLS             TLSConfig     `mapstructure:"tls"`
	UnixSocket      string        `mapstructure:"unix_socket"`   // 非空时优先于 Port,监听 unix socket
	ResponseMode    string        `mapstructure:"response_mode"` // business(默认) 或 rest,见 response.SetMode
}

ServerConfig 服务配置

func (ServerConfig) EffectiveIdleTimeout added in v1.1.0

func (c ServerConfig) EffectiveIdleTimeout() time.Duration

EffectiveIdleTimeout 返回生效的空闲超时(零值回退默认)

func (ServerConfig) EffectiveMaxHeaderBytes added in v1.1.0

func (c ServerConfig) EffectiveMaxHeaderBytes() int

EffectiveMaxHeaderBytes 返回生效的最大请求头字节数(零值回退默认)

func (ServerConfig) EffectiveReadTimeout added in v1.1.0

func (c ServerConfig) EffectiveReadTimeout() time.Duration

EffectiveReadTimeout 返回生效的读超时(零值回退默认)

func (ServerConfig) EffectiveShutdownTimeout added in v1.1.0

func (c ServerConfig) EffectiveShutdownTimeout() time.Duration

EffectiveShutdownTimeout 返回生效的关闭超时(零值回退默认)

func (ServerConfig) EffectiveWriteTimeout added in v1.1.0

func (c ServerConfig) EffectiveWriteTimeout() time.Duration

EffectiveWriteTimeout 返回生效的写超时(零值回退默认)

type StorageConfig

type StorageConfig struct {
	Driver string             `mapstructure:"driver"` // local 或 oss
	Local  LocalStorageConfig `mapstructure:"local"`
	OSS    OSSStorageConfig   `mapstructure:"oss"`
}

StorageConfig 文件存储配置

type TLSConfig added in v1.1.0

type TLSConfig struct {
	Enabled  bool   `mapstructure:"enabled"`
	CertFile string `mapstructure:"cert_file"`
	KeyFile  string `mapstructure:"key_file"`
}

TLSConfig HTTPS/TLS 配置

type UploadConfig

type UploadConfig struct {
	MaxFileSize       int      `mapstructure:"max_file_size"`       // 最大图片大小(MB)
	MaxVideoSize      int      `mapstructure:"max_video_size"`      // 最大视频大小(MB)
	MaxAvatarSize     int      `mapstructure:"max_avatar_size"`     // 最大头像大小(MB)
	AllowedImageTypes []string `mapstructure:"allowed_image_types"` // 允许的图片 MIME 类型
	AllowedVideoTypes []string `mapstructure:"allowed_video_types"` // 允许的视频 MIME 类型
}

UploadConfig 上传配置

Jump to

Keyboard shortcuts

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