hi-server/pkg/tool/sliceReflectToStruct.go
shanshanzhong 1d81df6664
Some checks failed
Build docker and publish / build (20.15.1) (push) Has been cancelled
add:添加短链接服务
2026-01-24 00:32:08 -08:00

51 lines
1.5 KiB
Go

package tool
import (
"reflect"
"strconv"
"github.com/goccy/go-json"
"github.com/perfect-panel/server/internal/model/system"
)
func SystemConfigSliceReflectToStruct(slice []*system.System, structType any) {
v := reflect.ValueOf(structType).Elem()
for _, config := range slice {
field := v.FieldByName(config.Key)
if field.Kind() == reflect.Ptr && field.Type().Elem().Kind() == reflect.Bool {
if config.Value == "" {
field.Set(reflect.Zero(field.Type()))
} else {
boolValue, _ := strconv.ParseBool(config.Value)
field.Set(reflect.ValueOf(&boolValue))
}
continue
}
if field.IsValid() && field.CanSet() {
switch field.Kind() {
case reflect.String:
field.SetString(config.Value)
case reflect.Bool:
boolValue, _ := strconv.ParseBool(config.Value)
field.SetBool(boolValue)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
intValue, _ := strconv.ParseInt(config.Value, 10, 64)
field.SetInt(intValue)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
uintValue, _ := strconv.ParseUint(config.Value, 10, 64)
field.SetUint(uintValue)
case reflect.Float32, reflect.Float64:
floatValue, _ := strconv.ParseFloat(config.Value, 64)
field.SetFloat(floatValue)
default:
// For interface, struct, map, slice, array - try JSON unmarshal
if config.Value != "" {
_ = json.Unmarshal([]byte(config.Value), field.Addr().Interface())
}
}
}
}
}