-
Notifications
You must be signed in to change notification settings - Fork 0
xenv
omeyang edited this page Sep 17, 2026
·
1 revision
稳定性:Stable · 覆盖率:95.6% · 源码:
pkg/context/xenv
环境变量读取与解析。带类型转换、默认值、必填校验。
- 配置加载阶段读取环境变量
- 兼容
os.Getenv但更安全(类型转换 / 默认 / 必填)
import "github.com/omeyang/xkit/pkg/context/xenv"
addr := xenv.String("LISTEN_ADDR", ":8080")
timeout := xenv.Duration("TIMEOUT", 30*time.Second)
debug := xenv.Bool("DEBUG", false)
token, err := xenv.Required("API_TOKEN")
if err != nil { /* missing */ }| 名称 | 说明 |
|---|---|
String / Int / Bool / Duration / Float64 |
带默认值 |
Required(key) (string, error) |
必填,缺失返错 |
MustRequired(key) string |
panic 版(启动期可用) |
-
早失败:
Required在启动期触发,远好过运行时空值 -
类型安全:避免手动
strconv.Atoi(os.Getenv(...))模板代码