plugin/utils/sort_struct.go

63 lines
1.3 KiB
Go

package utils
import (
"fmt"
"reflect"
"sort"
"strings"
)
type KeyValue struct {
Key string
Value string
}
func LowercaseFirstLetter(s string) string {
if len(s) == 0 {
return s
}
firstLetter := strings.ToLower(s[:1])
return firstLetter + s[1:]
}
func SortStruct(data any) []KeyValue {
v := reflect.ValueOf(data).Elem()
t := v.Type()
var kv []KeyValue
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
key := LowercaseFirstLetter(t.Field(i).Name)
value := fmt.Sprintf("%v", field.Interface())
kv = append(kv, KeyValue{Key: key, Value: value})
}
sort.SliceStable(kv, func(i, j int) bool {
return kv[i].Key < kv[j].Key
})
return kv
}
func SortStructJsonTag(data any) []KeyValue {
// 获取 data 结构体的类型和值
dataType := reflect.TypeOf(data).Elem()
dataValue := reflect.ValueOf(data).Elem()
var kv []KeyValue
for i := 0; i < dataType.NumField(); i++ {
field := dataType.Field(i)
// 获取字段的值
fieldValue := dataValue.FieldByName(field.Name).Interface()
// 获取 JSON 字段名
jsonTagName := field.Tag.Get("json")
if jsonTagName != "" {
kv = append(kv, KeyValue{Key: jsonTagName, Value: fmt.Sprintf("%v", fieldValue)})
}
}
// 排序
sort.SliceStable(kv, func(i, j int) bool {
return kv[i].Key < kv[j].Key
})
return kv
}