refactor server command (#206)
This commit is contained in:
+61
-52
@@ -19,6 +19,7 @@ package config
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/viper"
|
||||
@@ -29,103 +30,111 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
// ConfigName holds the name of the configuration file.
|
||||
ConfigName = ""
|
||||
|
||||
// ConfigType specifies the type/format of the configuration file.
|
||||
ConfigType = ""
|
||||
|
||||
// ConfigPath denotes the path to the configuration file.
|
||||
ConfigPath = ""
|
||||
|
||||
// ERROR
|
||||
ErrInvalidDirectory = errors.New("invalid directory path")
|
||||
ErrMissingConfigName = errors.New("config name not specified")
|
||||
)
|
||||
|
||||
// Init initializes the configuration settings.
|
||||
type Manager struct {
|
||||
App string
|
||||
EnvPrefix string
|
||||
Path string
|
||||
Name string
|
||||
WriteConfig bool
|
||||
|
||||
Viper *viper.Viper
|
||||
}
|
||||
|
||||
// New initializes the configuration settings.
|
||||
// It sets up the name, type, and path for the configuration file.
|
||||
func Init(name, _type, path string) error {
|
||||
if len(name) == 0 {
|
||||
return ErrMissingConfigName
|
||||
}
|
||||
|
||||
if len(_type) == 0 {
|
||||
_type = DefaultConfigType
|
||||
func New(app, path, name, envPrefix string, writeConfig bool) (*Manager, error) {
|
||||
if len(app) == 0 {
|
||||
return nil, ErrMissingConfigName
|
||||
}
|
||||
|
||||
v := viper.New()
|
||||
v.SetConfigType(DefaultConfigType)
|
||||
var err error
|
||||
|
||||
// Path
|
||||
if len(path) == 0 {
|
||||
path, err = os.UserHomeDir()
|
||||
if err != nil {
|
||||
path = os.TempDir()
|
||||
}
|
||||
path += string(os.PathSeparator) + "." + name
|
||||
path += string(os.PathSeparator) + "." + app
|
||||
}
|
||||
if err := PrepareDir(path); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
v.AddConfigPath(path)
|
||||
|
||||
// Name
|
||||
if len(name) == 0 {
|
||||
name = app
|
||||
}
|
||||
v.SetConfigName(name)
|
||||
|
||||
// Env
|
||||
if len(envPrefix) != 0 {
|
||||
v.SetEnvPrefix(strings.ToUpper(app))
|
||||
v.AutomaticEnv()
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
}
|
||||
|
||||
ConfigName = name
|
||||
ConfigType = _type
|
||||
ConfigPath = path
|
||||
return nil
|
||||
return &Manager{
|
||||
App: app,
|
||||
EnvPrefix: envPrefix,
|
||||
Path: path,
|
||||
Name: name,
|
||||
Viper: v,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Load loads the configuration from the previously initialized file.
|
||||
// It unmarshals the configuration into the provided conf interface.
|
||||
func Load(conf interface{}) error {
|
||||
viper.SetConfigName(ConfigName)
|
||||
viper.SetConfigType(ConfigType)
|
||||
viper.AddConfigPath(ConfigPath)
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
if err := viper.SafeWriteConfig(); err != nil {
|
||||
return err
|
||||
func (c *Manager) Load(conf interface{}) error {
|
||||
if err := c.Viper.ReadInConfig(); err != nil {
|
||||
if c.WriteConfig {
|
||||
if err := c.Viper.SafeWriteConfig(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := viper.Unmarshal(conf); err != nil {
|
||||
if err := c.Viper.Unmarshal(conf, decoderConfig()); err != nil {
|
||||
return err
|
||||
}
|
||||
SetDefault(conf)
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadFile loads the configuration from a specified file.
|
||||
// It unmarshals the configuration into the provided conf interface.
|
||||
func LoadFile(file string, conf interface{}) error {
|
||||
viper.SetConfigFile(file)
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
func (c *Manager) LoadFile(file string, conf interface{}) error {
|
||||
c.Viper.SetConfigFile(file)
|
||||
if err := c.Viper.ReadInConfig(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := viper.Unmarshal(conf); err != nil {
|
||||
if err := c.Viper.Unmarshal(conf, decoderConfig()); err != nil {
|
||||
return err
|
||||
}
|
||||
SetDefault(conf)
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetConfig sets a configuration key to a specified value.
|
||||
// It also writes the updated configuration back to the file.
|
||||
func SetConfig(key string, value interface{}) error {
|
||||
viper.Set(key, value)
|
||||
if err := viper.WriteConfig(); err != nil {
|
||||
return err
|
||||
func (c *Manager) SetConfig(key string, value interface{}) error {
|
||||
c.Viper.Set(key, value)
|
||||
if c.WriteConfig {
|
||||
if err := c.Viper.WriteConfig(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResetConfig resets the configuration to empty.
|
||||
func ResetConfig() error {
|
||||
viper.Reset()
|
||||
viper.SetConfigName(ConfigName)
|
||||
viper.SetConfigType(ConfigType)
|
||||
viper.AddConfigPath(ConfigPath)
|
||||
return viper.WriteConfig()
|
||||
}
|
||||
|
||||
// GetConfig retrieves all configuration settings as a map.
|
||||
func GetConfig() map[string]interface{} {
|
||||
return viper.AllSettings()
|
||||
func (c *Manager) GetConfig() map[string]interface{} {
|
||||
return c.Viper.AllSettings()
|
||||
}
|
||||
|
||||
// PrepareDir ensures that the specified directory path exists.
|
||||
|
||||
+8
-226
@@ -17,235 +17,17 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strconv"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// DefaultTag is the default tag used to identify default values for struct fields.
|
||||
var DefaultTag string
|
||||
|
||||
func init() {
|
||||
DefaultTag = "default"
|
||||
}
|
||||
|
||||
// SetDefaultTag updates the tag used to identify default values.
|
||||
func SetDefaultTag(tag string) {
|
||||
DefaultTag = tag
|
||||
}
|
||||
|
||||
// SetDefault sets the default values for a given interface{}.
|
||||
// The interface{} must be a pointer to a struct, bcs the default values are SET on the struct fields.
|
||||
func SetDefault(v interface{}) {
|
||||
if v == nil {
|
||||
return
|
||||
func SetDefaults(v *viper.Viper, c any, defaults map[string]any) {
|
||||
keys := GetStructKeys(reflect.TypeOf(c), "mapstructure", "squash")
|
||||
for _, key := range keys {
|
||||
v.SetDefault(key, nil)
|
||||
}
|
||||
|
||||
val := reflect.ValueOf(v)
|
||||
if val.Kind() == reflect.Ptr {
|
||||
val = val.Elem()
|
||||
}
|
||||
|
||||
setDefault(val, "")
|
||||
}
|
||||
|
||||
// setDefault recursively sets default values based on the struct's tags.
|
||||
func setDefault(val reflect.Value, tag string) {
|
||||
|
||||
if !val.CanSet() {
|
||||
return
|
||||
}
|
||||
|
||||
switch val.Kind() {
|
||||
case reflect.Struct:
|
||||
handleStruct(val, tag)
|
||||
case reflect.Ptr:
|
||||
handlePtr(val, tag)
|
||||
case reflect.Interface:
|
||||
handleInterface(val, tag)
|
||||
case reflect.Map:
|
||||
handleMap(val, tag)
|
||||
case reflect.Slice, reflect.Array:
|
||||
handleSliceArray(val, tag)
|
||||
default:
|
||||
handleSimpleType(val, tag)
|
||||
for key := range defaults {
|
||||
v.SetDefault(key, defaults[key])
|
||||
}
|
||||
}
|
||||
|
||||
// handleSimpleType handles the assignment of default values for simple data types.
|
||||
func handleSimpleType(val reflect.Value, tag string) {
|
||||
|
||||
if len(tag) == 0 || !val.IsZero() || !val.CanSet() {
|
||||
return
|
||||
}
|
||||
|
||||
// Assign appropriate default values based on the data type.
|
||||
switch val.Kind() {
|
||||
case reflect.String:
|
||||
val.SetString(tag)
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
if intValue, err := strconv.ParseInt(tag, 10, 64); err == nil {
|
||||
val.SetInt(intValue)
|
||||
}
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
if uintVal, err := strconv.ParseUint(tag, 10, 64); err == nil {
|
||||
val.SetUint(uintVal)
|
||||
}
|
||||
case reflect.Float32, reflect.Float64:
|
||||
if floatValue, err := strconv.ParseFloat(tag, 64); err == nil {
|
||||
val.SetFloat(floatValue)
|
||||
}
|
||||
case reflect.Bool:
|
||||
if boolVal, err := strconv.ParseBool(tag); err == nil {
|
||||
val.SetBool(boolVal)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleStruct processes struct type fields and sets default values based on their tags.
|
||||
func handleStruct(val reflect.Value, tag string) {
|
||||
|
||||
if val.Kind() != reflect.Struct {
|
||||
return
|
||||
}
|
||||
|
||||
if !val.IsZero() || len(tag) == 0 {
|
||||
typ := val.Type()
|
||||
for i := 0; i < val.NumField(); i++ {
|
||||
field := val.Field(i)
|
||||
fieldType := typ.Field(i)
|
||||
setDefault(field, fieldType.Tag.Get(DefaultTag))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if !val.CanSet() {
|
||||
return
|
||||
}
|
||||
|
||||
// If tag is provided, unmarshal the default value and set it.
|
||||
newStruct := reflect.New(val.Type()).Interface()
|
||||
if err := json.Unmarshal([]byte(tag), newStruct); err == nil {
|
||||
newStructVal := reflect.ValueOf(newStruct).Elem()
|
||||
for i := 0; i < newStructVal.NumField(); i++ {
|
||||
field := newStructVal.Field(i)
|
||||
fieldType := newStructVal.Type().Field(i)
|
||||
setDefault(field, fieldType.Tag.Get(DefaultTag))
|
||||
}
|
||||
val.Set(newStructVal)
|
||||
}
|
||||
}
|
||||
|
||||
// handleSliceArray sets default values for slice or array types.
|
||||
func handleSliceArray(val reflect.Value, tag string) {
|
||||
|
||||
if val.Kind() != reflect.Slice && val.Kind() != reflect.Array {
|
||||
return
|
||||
}
|
||||
|
||||
if !val.IsZero() || len(tag) == 0 {
|
||||
for i := 0; i < val.Len(); i++ {
|
||||
setDefault(val.Index(i), "")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if !val.CanSet() {
|
||||
return
|
||||
}
|
||||
|
||||
// array 提前初始化子结构体,解决 default 长度小于 array 长度的问题
|
||||
if val.Kind() == reflect.Array {
|
||||
for i := 0; i < val.Len(); i++ {
|
||||
setDefault(val.Index(i), "")
|
||||
}
|
||||
}
|
||||
|
||||
// If tag is provided, unmarshal the default value and set it.
|
||||
newSlice := reflect.New(reflect.SliceOf(val.Type().Elem())).Interface()
|
||||
if err := json.Unmarshal([]byte(tag), newSlice); err == nil {
|
||||
sliceValue := reflect.ValueOf(newSlice).Elem()
|
||||
for j := 0; j < sliceValue.Len(); j++ {
|
||||
v := sliceValue.Index(j)
|
||||
setDefault(v, "")
|
||||
if val.Kind() == reflect.Array {
|
||||
if j >= val.Len() {
|
||||
return
|
||||
}
|
||||
val.Index(j).Set(v)
|
||||
} else {
|
||||
val.Set(reflect.Append(val, v))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleMap sets default values for map types.
|
||||
func handleMap(val reflect.Value, tag string) {
|
||||
|
||||
if val.Kind() != reflect.Map {
|
||||
return
|
||||
}
|
||||
|
||||
if !val.IsZero() || len(tag) == 0 {
|
||||
for _, key := range val.MapKeys() {
|
||||
setDefault(val.MapIndex(key), "")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if !val.CanSet() {
|
||||
return
|
||||
}
|
||||
|
||||
// If tag is provided, unmarshal the default value and set it.
|
||||
newMap := reflect.New(val.Type()).Interface()
|
||||
if err := json.Unmarshal([]byte(tag), newMap); err == nil {
|
||||
newMapVal := reflect.ValueOf(newMap).Elem()
|
||||
for _, k := range newMapVal.MapKeys() {
|
||||
v := newMapVal.MapIndex(k)
|
||||
setDefault(v, "")
|
||||
}
|
||||
val.Set(newMapVal)
|
||||
}
|
||||
}
|
||||
|
||||
// handlePtr handles pointer types and sets default values based on their tags.
|
||||
func handlePtr(val reflect.Value, tag string) {
|
||||
|
||||
if val.Kind() != reflect.Ptr {
|
||||
return
|
||||
}
|
||||
|
||||
if !val.IsZero() || len(tag) == 0 || !val.CanSet() {
|
||||
return
|
||||
}
|
||||
|
||||
// If tag is provided, unmarshal the default value and set it.
|
||||
newPtr := reflect.New(val.Type()).Interface()
|
||||
if err := json.Unmarshal([]byte(tag), newPtr); err == nil {
|
||||
newPtrVal := reflect.ValueOf(newPtr).Elem()
|
||||
setDefault(newPtrVal, "")
|
||||
val.Set(newPtrVal)
|
||||
}
|
||||
}
|
||||
|
||||
// handleInterface processes interface types and sets default values based on their tags.
|
||||
// support pointer interface only, bcs the default values are SET on the struct fields.
|
||||
func handleInterface(val reflect.Value, tag string) {
|
||||
|
||||
if val.Kind() != reflect.Interface {
|
||||
return
|
||||
}
|
||||
|
||||
if val.IsNil() {
|
||||
return
|
||||
}
|
||||
|
||||
if val.Elem().Kind() != reflect.Ptr {
|
||||
return
|
||||
}
|
||||
|
||||
// Recursively set the default for the inner value of the interface.
|
||||
setDefault(reflect.ValueOf(val.Elem().Interface()).Elem(), tag)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const sep = "."
|
||||
|
||||
// GetStructKeys returns all keys in a nested struct type, taking the name from the tag name or
|
||||
// the field name. It handles an additional suffix squashValue like mapstructure does: if
|
||||
// present on an embedded struct, name components for that embedded struct should not be
|
||||
// included. It does not handle maps, does chase pointers, but does not check for loops in
|
||||
// nesting.
|
||||
func GetStructKeys(typ reflect.Type, tag, squashValue string) []string {
|
||||
return appendStructKeys(typ, tag, ","+squashValue, nil, nil)
|
||||
}
|
||||
|
||||
// appendStructKeys recursively appends to keys all keys of nested struct type typ, taking tag
|
||||
// and squashValue from GetStructKeys. prefix holds all components of the path from the typ
|
||||
// passed to GetStructKeys down to this typ.
|
||||
func appendStructKeys(typ reflect.Type, tag, squashValue string, prefix []string, keys []string) []string {
|
||||
// Dereference any pointers. This is a finite loop: Go types are well-founded.
|
||||
for ; typ.Kind() == reflect.Ptr; typ = typ.Elem() {
|
||||
}
|
||||
|
||||
// Handle only struct containers; terminate the recursion on anything else.
|
||||
if typ.Kind() != reflect.Struct {
|
||||
return append(keys, strings.Join(prefix, sep))
|
||||
}
|
||||
|
||||
for i := 0; i < typ.NumField(); i++ {
|
||||
fieldType := typ.Field(i)
|
||||
var (
|
||||
// fieldName is the name to use for the field.
|
||||
fieldName string
|
||||
// If squash is true, squash the sub-struct no additional accessor.
|
||||
squash bool
|
||||
ok bool
|
||||
)
|
||||
if fieldName, ok = fieldType.Tag.Lookup(tag); ok {
|
||||
if strings.HasSuffix(fieldName, squashValue) {
|
||||
squash = true
|
||||
fieldName = strings.TrimSuffix(fieldName, squashValue)
|
||||
}
|
||||
} else {
|
||||
fieldName = strings.ToLower(fieldType.Name)
|
||||
}
|
||||
// Update prefix to recurse into this field.
|
||||
if !squash {
|
||||
prefix = append(prefix, fieldName)
|
||||
}
|
||||
keys = appendStructKeys(fieldType.Type, tag, squashValue, prefix, keys)
|
||||
// Restore prefix.
|
||||
if !squash {
|
||||
prefix = prefix[:len(prefix)-1]
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// ValidateMissingRequiredKeys returns all keys of value in GetStructKeys format that have an
|
||||
// additional required tag set but are unset.
|
||||
func ValidateMissingRequiredKeys(value interface{}, tag, squashValue string) []string {
|
||||
return appendStructKeysIfZero(reflect.ValueOf(value), tag, ","+squashValue, "validate", "required", nil, nil)
|
||||
}
|
||||
|
||||
// isScalar returns true if kind is "scalar", i.e. has no Elem(). This
|
||||
// recites the list from reflect/type.go and may start to give incorrect
|
||||
// results if new kinds are added to the language.
|
||||
func isScalar(kind reflect.Kind) bool {
|
||||
switch kind {
|
||||
case reflect.Array:
|
||||
case reflect.Chan:
|
||||
case reflect.Map:
|
||||
case reflect.Ptr:
|
||||
case reflect.Slice:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func appendStructKeysIfZero(value reflect.Value, tag, squashValue, validateTag, requiredValue string, prefix []string, keys []string) []string {
|
||||
// finite loop: Go types are well-founded.
|
||||
for value.Kind() == reflect.Ptr {
|
||||
if value.IsZero() { // If required, would already have errored out.
|
||||
return keys
|
||||
}
|
||||
value = value.Elem()
|
||||
}
|
||||
|
||||
if !isScalar(value.Kind()) {
|
||||
// Why use Type().Elem() when reflect.Value provides a perfectly good Elem()
|
||||
// method? The two are *not* the same, e.g. for nil pointers value.Elem() is
|
||||
// invalid and has no Kind(). (See https://play.golang.org/p/M3ZV19AZAW0)
|
||||
if !isScalar(value.Type().Elem().Kind()) {
|
||||
// TODO(ariels): Possible to add, but need to define the semantics. One
|
||||
// way might be to validate each field according to its type.
|
||||
panic("No support for detecting required keys inside " + value.Kind().String() + " of structs")
|
||||
}
|
||||
}
|
||||
|
||||
// Handle only struct containers; terminate the recursion on anything else.
|
||||
if value.Kind() != reflect.Struct {
|
||||
return keys
|
||||
}
|
||||
|
||||
for i := 0; i < value.NumField(); i++ {
|
||||
fieldType := value.Type().Field(i)
|
||||
fieldValue := value.Field(i)
|
||||
|
||||
var (
|
||||
// fieldName is the name to use for the field.
|
||||
fieldName string
|
||||
// If squash is true, squash the sub-struct no additional accessor.
|
||||
squash bool
|
||||
ok bool
|
||||
)
|
||||
if fieldName, ok = fieldType.Tag.Lookup(tag); ok {
|
||||
if strings.HasSuffix(fieldName, squashValue) {
|
||||
squash = true
|
||||
fieldName = strings.TrimSuffix(fieldName, squashValue)
|
||||
}
|
||||
} else {
|
||||
fieldName = strings.ToLower(fieldType.Name)
|
||||
}
|
||||
|
||||
// Perform any needed validations.
|
||||
if validationsString, ok := fieldType.Tag.Lookup(validateTag); ok {
|
||||
for _, validation := range strings.Split(validationsString, ",") {
|
||||
// Validate "required" field.
|
||||
if validation == requiredValue && fieldValue.IsZero() {
|
||||
keys = append(keys, strings.Join(append(prefix, fieldName), sep))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update prefix to recurse into this field.
|
||||
if !squash {
|
||||
prefix = append(prefix, fieldName)
|
||||
}
|
||||
keys = appendStructKeysIfZero(fieldValue, tag, squashValue, validateTag, requiredValue, prefix, keys)
|
||||
// Restore prefix.
|
||||
if !squash {
|
||||
prefix = prefix[:len(prefix)-1]
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// DecodeStringToMap returns a DecodeHookFunc that converts a string to a map[string]string.
|
||||
// The string is expected to be a comma-separated list of key-value pairs, where the key and value
|
||||
// are separated by an equal sign.
|
||||
func DecodeStringToMap() mapstructure.DecodeHookFunc {
|
||||
return func(f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error) {
|
||||
// check if field is a string and target is a map
|
||||
if f != reflect.String || t != reflect.Map {
|
||||
return data, nil
|
||||
}
|
||||
// check if target is map[string]string
|
||||
if t != reflect.TypeOf(map[string]string{}).Kind() {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
raw := data.(string)
|
||||
if raw == "" {
|
||||
return map[string]string{}, nil
|
||||
}
|
||||
// parse raw string as key1=value1,key2=value2
|
||||
const pairSep = ","
|
||||
const valueSep = "="
|
||||
pairs := strings.Split(raw, pairSep)
|
||||
m := make(map[string]string, len(pairs))
|
||||
for _, pair := range pairs {
|
||||
key, value, found := strings.Cut(pair, valueSep)
|
||||
if !found {
|
||||
return nil, fmt.Errorf("invalid key-value pair: %s", pair)
|
||||
}
|
||||
m[strings.TrimSpace(key)] = strings.TrimSpace(value)
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
}
|
||||
|
||||
// StringToSliceWithBracketHookFunc returns a DecodeHookFunc that converts a string to a slice of strings.
|
||||
// Useful when configuration values are provided as JSON arrays in string form, but need to be parsed into slices.
|
||||
// The string is expected to be a JSON array.
|
||||
// If the string is empty, an empty slice is returned.
|
||||
// If the string cannot be parsed as a JSON array, the original data is returned unchanged.
|
||||
func StringToSliceWithBracketHookFunc() mapstructure.DecodeHookFunc {
|
||||
return func(f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error) {
|
||||
if f != reflect.String || t != reflect.Slice {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
raw := data.(string)
|
||||
if raw == "" {
|
||||
return []string{}, nil
|
||||
}
|
||||
var result any
|
||||
err := json.Unmarshal([]byte(raw), &result)
|
||||
if err != nil {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// Verify that the result matches the target (slice)
|
||||
if reflect.TypeOf(result).Kind() != t {
|
||||
return data, nil
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
// StringToStructHookFunc returns a DecodeHookFunc that converts a string to a struct.
|
||||
// Useful for parsing configuration values that are provided as JSON strings but need to be converted to sturcts.
|
||||
// The string is expected to be a JSON object that can be unmarshaled into the target struct.
|
||||
// If the string is empty, a new instance of the target struct is returned.
|
||||
// If the string cannot be parsed as a JSON object, the original data is returned unchanged.
|
||||
func StringToStructHookFunc() mapstructure.DecodeHookFunc {
|
||||
return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
|
||||
if f.Kind() != reflect.String ||
|
||||
(t.Kind() != reflect.Struct && !(t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.Struct)) {
|
||||
return data, nil
|
||||
}
|
||||
raw := data.(string)
|
||||
var val reflect.Value
|
||||
// Struct or the pointer to a struct
|
||||
if t.Kind() == reflect.Struct {
|
||||
val = reflect.New(t)
|
||||
} else {
|
||||
val = reflect.New(t.Elem())
|
||||
}
|
||||
|
||||
if raw == "" {
|
||||
return val, nil
|
||||
}
|
||||
var m map[string]interface{}
|
||||
err := json.Unmarshal([]byte(raw), &m)
|
||||
if err != nil {
|
||||
return data, nil
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
}
|
||||
|
||||
// CompositeDecodeHook 组合所有解码钩子
|
||||
func CompositeDecodeHook() mapstructure.DecodeHookFunc {
|
||||
return mapstructure.ComposeDecodeHookFunc(
|
||||
mapstructure.StringToTimeDurationHookFunc(),
|
||||
DecodeStringToMap(),
|
||||
StringToStructHookFunc(),
|
||||
StringToSliceWithBracketHookFunc(),
|
||||
)
|
||||
}
|
||||
|
||||
func decoderConfig() viper.DecoderConfigOption {
|
||||
return viper.DecodeHook(CompositeDecodeHook())
|
||||
}
|
||||
Reference in New Issue
Block a user