1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-15 02:02:27 +08:00

Add StructUtil for provide more rich functions (#79)

* add support json tag attribute for StructToMap function

* add the structutil to provide more rich functions and fixed #77
This commit is contained in:
zm
2023-03-13 19:28:37 +08:00
committed by GitHub
parent 1755dd249b
commit 924589d2da
9 changed files with 263 additions and 64 deletions

View File

@@ -11,9 +11,9 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/duke-git/lancet/v2/structutil"
"math"
"reflect"
"regexp"
"strconv"
"strings"
)
@@ -235,32 +235,7 @@ func ToMap[T any, K comparable, V any](array []T, iteratee func(T) (K, V)) map[K
// map key is specified same as struct field tag `json` value.
// Play: https://go.dev/play/p/KYGYJqNUBOI
func StructToMap(value any) (map[string]any, error) {
v := reflect.ValueOf(value)
t := reflect.TypeOf(value)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil, fmt.Errorf("data type %T not support, shuld be struct or pointer to struct", value)
}
result := make(map[string]any)
fieldNum := t.NumField()
pattern := `^[A-Z]`
regex := regexp.MustCompile(pattern)
for i := 0; i < fieldNum; i++ {
name := t.Field(i).Name
tag := t.Field(i).Tag.Get("json")
if tag == "" || strings.HasPrefix(tag, "-") || !regex.MatchString(name) {
continue
}
tag = strings.Split(tag, ",")[0]
result[tag] = v.Field(i).Interface()
}
return result, nil
return structutil.ToMap(value)
}
// MapToSlice convert map to slice based on iteratee function.