69 lines
1.7 KiB
Go
Raw Normal View History

2025-04-22 15:46:48 +08:00
package entity
import (
"fmt"
"gorm.io/gorm"
"reflect"
"strconv"
"time"
)
func parseStr2FieldValue(field reflect.StructField, rawValue any) (realSetValue reflect.Value) {
setValue := fmt.Sprintf("%v", rawValue)
var parsedValue any
switch field.Type.Kind() {
case reflect.Int:
v, _ := strconv.Atoi(setValue)
parsedValue = int(v)
case reflect.Int32:
v, _ := strconv.Atoi(setValue)
parsedValue = int32(v)
case reflect.Int8:
v, _ := strconv.Atoi(setValue)
parsedValue = int8(v)
case reflect.Int16:
v, _ := strconv.Atoi(setValue)
parsedValue = int16(v)
case reflect.Int64:
v, _ := strconv.Atoi(setValue)
parsedValue = int64(v)
case reflect.Uint:
v, _ := strconv.Atoi(setValue)
parsedValue = uint(v)
case reflect.Uint8:
v, _ := strconv.Atoi(setValue)
parsedValue = uint(v)
case reflect.Uint16:
v, _ := strconv.Atoi(setValue)
parsedValue = uint16(v)
case reflect.Uint32:
v, _ := strconv.Atoi(setValue)
parsedValue = uint32(v)
case reflect.Uint64:
v, _ := strconv.Atoi(setValue)
parsedValue = uint64(v)
case reflect.Bool:
parsedValue = setValue == "true"
case reflect.String:
parsedValue = setValue
case reflect.Float32:
v, _ := strconv.ParseFloat(setValue, 10)
parsedValue = float32(v)
case reflect.Float64:
v, _ := strconv.ParseFloat(setValue, 10)
parsedValue = float64(v)
case reflect.Struct:
typeName := field.Type.Name()
if typeName == "Time" {
return reflect.ValueOf(time.Now())
}
if typeName == "DeletedAt" {
return reflect.ValueOf(gorm.DeletedAt{})
}
fallthrough
default:
panic(fmt.Errorf("暂时不支持的前后端交互字段类型:%v, 类型名:%v", field.Type.Kind(), field.Type.Name()))
}
return reflect.ValueOf(parsedValue)
}