voucher/internal/pkg/helper/kvsort.go

61 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package helper
import (
"reflect"
"sort"
"strings"
)
func LowercaseFirstLetter(s string) string {
if len(s) == 0 {
return s
}
firstLetter := strings.ToLower(s[:1])
return firstLetter + s[1:]
}
// FieldKeyValue 定义一个结构体用于存储字段名和对应的值
type FieldKeyValue struct {
Key string
Value interface{}
}
// SortStructFieldsByKey 按照键名对结构体导出字段进行字典序排序,并返回键值对切片
func SortStructFieldsByKey(s interface{}) []FieldKeyValue {
// 获取结构体的反射值
value := reflect.ValueOf(s)
// 如果传入的是指针,获取指针指向的值
if value.Kind() == reflect.Ptr {
value = value.Elem()
}
// 检查是否为结构体
if value.Kind() != reflect.Struct {
return nil
}
// 获取结构体的类型
typ := value.Type()
// 存储字段名和对应的值
fieldKVs := make([]FieldKeyValue, 0, typ.NumField())
// 遍历结构体的所有字段
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
// 只处理导出的字段PkgPath 为空表示导出字段)
if field.PkgPath == "" {
// 获取字段名
fieldName := field.Name
// 获取字段的值
fieldValue := value.Field(i).Interface()
// 将字段名和对应的值存储到切片中
fieldKVs = append(fieldKVs, FieldKeyValue{
Key: LowercaseFirstLetter(fieldName),
Value: fieldValue,
})
}
}
// 对键值对切片按照键名进行字典序排序
sort.Slice(fieldKVs, func(i, j int) bool {
return fieldKVs[i].Key < fieldKVs[j].Key
})
return fieldKVs
}