1
0

feat: 引入 Viper 实现多层配置管理

引入 Viper 配置管理框架,支持 CLI 参数、环境变量、配置文件和默认值四种配置方式。

主要变更:
- 引入 Viper、pflag、validator、mapstructure 依赖
- 实现配置优先级:CLI > ENV > File > Default
- 所有 13 个配置项支持 CLI 参数和环境变量
- 规范化命名:server.port → NEX_SERVER_PORT → --server-port
- 使用结构体验证器进行配置验证
- 添加配置摘要输出功能

新增能力:
- cli-config: 命令行参数配置支持
- env-config: 环境变量配置支持(符合 12-Factor App)
- config-priority: 配置优先级管理

修改能力:
- config-management: 扩展为多层配置源支持

使用示例:
  ./server --server-port 9000 --log-level debug
  export NEX_SERVER_PORT=9000 && ./server
  ./server --config /path/to/custom.yaml
This commit is contained in:
2026-04-20 18:04:42 +08:00
parent aea360bce8
commit cfb0edf802
15 changed files with 468 additions and 577 deletions

View File

@@ -4,8 +4,12 @@ go 1.26.2
require (
github.com/gin-gonic/gin v1.12.0
github.com/go-playground/validator/v10 v10.30.2
github.com/google/uuid v1.6.0
github.com/mitchellh/mapstructure v1.5.0
github.com/pressly/goose/v3 v3.27.0
github.com/spf13/pflag v1.0.10
github.com/spf13/viper v1.21.0
github.com/stretchr/testify v1.11.1
go.uber.org/zap v1.27.1
gopkg.in/lumberjack.v2 v2.0.0
@@ -20,12 +24,13 @@ require (
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.2 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
@@ -39,14 +44,20 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/arch v0.22.0 // indirect
golang.org/x/crypto v0.49.0 // indirect
golang.org/x/net v0.51.0 // indirect