From d2d3002df5712e39ce0ceecb9b65eb779fd898d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 13 May 2025 15:02:29 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=B7=A5=E5=85=B7=E5=87=BD?= =?UTF-8?q?=E6=95=B0,=20=E6=94=AF=E6=8C=81=E5=B0=86=20map/struct=20?= =?UTF-8?q?=E6=89=93=E6=95=A3,=20=E4=BD=9C=E4=B8=BA=E8=84=9A=E6=9C=AC?= =?UTF-8?q?=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utility.go | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 utility.go diff --git a/utility.go b/utility.go new file mode 100644 index 0000000..a04c28a --- /dev/null +++ b/utility.go @@ -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 +}