68 lines
2.3 KiB
Go
68 lines
2.3 KiB
Go
// Package config 提供 YAML 配置读取,不发布应用配置或修改进程环境。
|
|
package config
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
"reflect"
|
|
|
|
fault "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure"
|
|
"github.com/goccy/go-yaml"
|
|
)
|
|
|
|
const (
|
|
// CodeTarget 表示配置接收对象无效。
|
|
CodeTarget = 900001
|
|
// CodeRead 表示读取配置文件失败。
|
|
CodeRead = 900002
|
|
// CodeDecode 表示配置内容解析失败。
|
|
CodeDecode = 900003
|
|
// CodeDocuments 表示配置包含多份 YAML 文档。
|
|
CodeDocuments = 900004
|
|
)
|
|
|
|
// Options 是配置读取行为;不会加载 .env 或执行应用校验。
|
|
type Options struct {
|
|
AllowUnknownFields bool `json:"allow_unknown_fields" dc:"是否接受未在接收结构体声明的配置项"`
|
|
DisableEnvExpansion bool `json:"disable_env_expansion" dc:"是否禁用已有进程环境变量展开"`
|
|
}
|
|
|
|
// Load 读取单份 YAML 到调用方结构体,默认拒绝未知字段。
|
|
// 入参: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"))
|
|
}
|
|
content, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return fault.Wrap(CodeRead, "read configuration file failed", err)
|
|
}
|
|
if !options.DisableEnvExpansion {
|
|
content = []byte(os.ExpandEnv(string(content)))
|
|
}
|
|
var (
|
|
decodeOptions []yaml.DecodeOption
|
|
)
|
|
if !options.AllowUnknownFields {
|
|
decodeOptions = append(decodeOptions, yaml.DisallowUnknownField())
|
|
}
|
|
decoder := yaml.NewDecoder(bytes.NewReader(content), decodeOptions...)
|
|
if err = decoder.Decode(target); err != nil {
|
|
return fault.Wrap(CodeDecode, "decode YAML configuration failed", err)
|
|
}
|
|
var (
|
|
extra any
|
|
)
|
|
if err = decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
|
if err == nil {
|
|
err = errors.New("multiple YAML documents are not supported")
|
|
}
|
|
return fault.Wrap(CodeDocuments, "validate YAML document count failed", err)
|
|
}
|
|
return nil
|
|
}
|