1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-03-01 00:35:28 +08:00

Merge branch 'main' into v2

This commit is contained in:
dudaodong
2023-03-11 20:14:32 +08:00
3 changed files with 35 additions and 19 deletions
+4 -3
View File
@@ -253,10 +253,11 @@ func StructToMap(value any) (map[string]any, error) {
for i := 0; i < fieldNum; i++ { for i := 0; i < fieldNum; i++ {
name := t.Field(i).Name name := t.Field(i).Name
tag := t.Field(i).Tag.Get("json") tag := t.Field(i).Tag.Get("json")
if regex.MatchString(name) && tag != "" { if tag == "" || strings.HasPrefix(tag, "-") || !regex.MatchString(name) {
//result[name] = v.Field(i).Interface() continue
result[tag] = v.Field(i).Interface()
} }
tag = strings.Split(tag, ",")[0]
result[tag] = v.Field(i).Interface()
} }
return result, nil return result, nil
+21 -2
View File
@@ -180,6 +180,7 @@ func TestToMap(t *testing.T) {
func TestStructToMap(t *testing.T) { func TestStructToMap(t *testing.T) {
assert := internal.NewAssert(t, "TestStructToMap") assert := internal.NewAssert(t, "TestStructToMap")
t.Run("StructToMap", func(t *testing.T) {
type People struct { type People struct {
Name string `json:"name"` Name string `json:"name"`
age int age int
@@ -189,9 +190,27 @@ func TestStructToMap(t *testing.T) {
100, 100,
} }
pm, _ := StructToMap(p) pm, _ := StructToMap(p)
var expected = map[string]any{"name": "test"}
expected := map[string]any{"name": "test"}
assert.Equal(expected, pm) assert.Equal(expected, pm)
})
t.Run("StructToMapWithJsonAttr", func(t *testing.T) {
type People struct {
Name string `json:"name,omitempty"` // json tag with attribute
Phone string `json:"phone"` // json tag without attribute
Sex string `json:"-"` // ignore
age int // no tag
}
p := People{
"test",
"1111",
"male",
100,
}
pm, _ := StructToMap(p)
var expected = map[string]any{"name": "test", "phone": "1111"}
assert.Equal(expected, pm)
})
} }
func TestMapToSlice(t *testing.T) { func TestMapToSlice(t *testing.T) {
+1 -5
View File
@@ -19,15 +19,11 @@ func ExampleContext() {
return errors.New("error occurs") return errors.New("error occurs")
} }
err := Retry(increaseNumber, Retry(increaseNumber,
RetryDuration(time.Microsecond*50), RetryDuration(time.Microsecond*50),
Context(ctx), Context(ctx),
) )
if err != nil {
return
}
fmt.Println(number) fmt.Println(number)
// Output: // Output: