1 parent
bedcf4dd83
commit
d2a9033695
23 files changed
+1544
-6
No files matched your search
+30
-3
@@ -33,14 +33,41 @@ type Options struct {
|
||||
// 入参:path 为文件路径,target 为非空结构体指针,options 为解码选项。
|
||||
// 返回:读取或解析失败返回内部场景错误,不输出配置内容。
|
||||
func Load(path string, target any, options Options) error {
|
||||
value := reflect.ValueOf(target)
|
||||
if !value.IsValid() || value.Kind() != reflect.Ptr || value.IsNil() || value.Elem().Kind() != reflect.Struct {
|
||||
return fault.Wrap(CodeTarget, "validate configuration receiver failed", errors.New("configuration target must be a non-nil struct pointer"))
|
||||
if err := validateTarget(target); err != nil {
|
||||
return err
|
||||
}
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return fault.Wrap(CodeRead, "read configuration file failed", err)
|
||||
}
|
||||
return decodeContent(content, target, options)
|
||||
}
|
||||
|
||||
// Decode 从已有字节解码单份 YAML,使用与 Load 相同的严格字段与环境变量规则。
|
||||
// 入参:content 为调用方读取的只读快照,target 为非空结构体指针,options 为解码选项。
|
||||
// 返回:目标或解码失败的内部场景错误;不修改 content、进程环境或关闭调用方资源。
|
||||
// 失败可能已写入部分 target,调用方应丢弃该结果;本函数不缓存内容。
|
||||
func Decode(content []byte, target any, options Options) error {
|
||||
if err := validateTarget(target); err != nil {
|
||||
return err
|
||||
}
|
||||
return decodeContent(content, target, options)
|
||||
}
|
||||
|
||||
// validateTarget 检查配置接收边界;入参为异构结构体指针,返回无效目标错误。
|
||||
func validateTarget(target any) error {
|
||||
value := reflect.ValueOf(target)
|
||||
if !value.IsValid() || value.Kind() != reflect.Ptr || value.IsNil() || value.Elem().Kind() != reflect.Struct {
|
||||
return fault.Wrap(CodeTarget, "validate configuration receiver failed", errors.New("configuration target must be a non-nil struct pointer"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeContent 统一执行解码;入参为字节快照、已验证的目标和解码选项,返回解析错误。
|
||||
func decodeContent(content []byte, target any, options Options) error {
|
||||
var (
|
||||
err error
|
||||
)
|
||||
if !options.DisableEnvExpansion {
|
||||
content = []byte(os.ExpandEnv(string(content)))
|
||||
}
|
||||
|
||||