1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-23 13:52:26 +08:00

Compare commits

...

3 Commits

Author SHA1 Message Date
dudaodong
77f32f4cc6 Merge branch 'main' into v2 2023-03-11 20:14:32 +08:00
zm
1755dd249b add support json tag attribute for StructToMap function (#78) 2023-03-11 20:08:41 +08:00
dudaodong
3857b342f6 fix: fix ExampleContext failed 2023-03-01 11:45:02 +08:00
3 changed files with 35 additions and 19 deletions

View File

@@ -253,10 +253,11 @@ func StructToMap(value any) (map[string]any, error) {
for i := 0; i < fieldNum; i++ {
name := t.Field(i).Name
tag := t.Field(i).Tag.Get("json")
if regex.MatchString(name) && tag != "" {
//result[name] = v.Field(i).Interface()
result[tag] = v.Field(i).Interface()
if tag == "" || strings.HasPrefix(tag, "-") || !regex.MatchString(name) {
continue
}
tag = strings.Split(tag, ",")[0]
result[tag] = v.Field(i).Interface()
}
return result, nil

View File

@@ -180,18 +180,37 @@ func TestToMap(t *testing.T) {
func TestStructToMap(t *testing.T) {
assert := internal.NewAssert(t, "TestStructToMap")
type People struct {
Name string `json:"name"`
age int
}
p := People{
"test",
100,
}
pm, _ := StructToMap(p)
t.Run("StructToMap", func(t *testing.T) {
type People struct {
Name string `json:"name"`
age int
}
p := People{
"test",
100,
}
pm, _ := StructToMap(p)
var expected = map[string]any{"name": "test"}
assert.Equal(expected, pm)
})
expected := map[string]any{"name": "test"}
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) {

View File

@@ -19,15 +19,11 @@ func ExampleContext() {
return errors.New("error occurs")
}
err := Retry(increaseNumber,
Retry(increaseNumber,
RetryDuration(time.Microsecond*50),
Context(ctx),
)
if err != nil {
return
}
fmt.Println(number)
// Output: