增加工具函数, 支持将 map/struct 打散, 作为脚本参数
This commit is contained in:
parent
00b00a2503
commit
d2d3002df5
68
utility.go
Normal file
68
utility.go
Normal file
@ -0,0 +1,68 @@
|
||||
// Package lua ...
|
||||
//
|
||||
// Description : lua ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 2025-05-13 14:50
|
||||
package lua
|
||||
|
||||
import "reflect"
|
||||
|
||||
// Map2ScriptParam map每一项转换为脚本参数
|
||||
func Map2ScriptParam(inputMap map[string]any) []ScriptParam {
|
||||
res := make([]ScriptParam, 0)
|
||||
for k, v := range inputMap {
|
||||
res = append(res, ScriptParam{
|
||||
Name: k,
|
||||
Value: v,
|
||||
})
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// Any2ScriptParam struct每一项转换为脚本参数
|
||||
// 仅支持 map / struct / *struct
|
||||
func Any2ScriptParam(input any) []ScriptParam {
|
||||
res := make([]ScriptParam, 0)
|
||||
|
||||
if nil == input {
|
||||
return res
|
||||
}
|
||||
dataVal := reflect.ValueOf(input)
|
||||
if dataVal.IsNil() {
|
||||
return res
|
||||
}
|
||||
dataType := reflect.TypeOf(input)
|
||||
if dataType.Kind() == reflect.Ptr {
|
||||
dataType = dataType.Elem()
|
||||
dataVal = dataVal.Elem()
|
||||
}
|
||||
if dataType.Kind() == reflect.Map {
|
||||
for _, key := range dataVal.MapKeys() {
|
||||
res = append(res, ScriptParam{
|
||||
Name: key.String(),
|
||||
Value: dataVal.MapIndex(key).Interface(),
|
||||
})
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
if dataType.Kind() == reflect.Struct {
|
||||
for i := 0; i < dataType.NumField(); i++ {
|
||||
paramName := dataType.Field(i).Name
|
||||
jsonTag := dataType.Field(i).Tag.Get("json")
|
||||
if jsonTag == "-" {
|
||||
continue
|
||||
}
|
||||
if jsonTag != "" {
|
||||
paramName = jsonTag
|
||||
}
|
||||
res = append(res, ScriptParam{
|
||||
Name: paramName,
|
||||
Value: dataVal.Field(i).Interface(),
|
||||
})
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user