-
-
Notifications
You must be signed in to change notification settings - Fork 274
/
issue104_test.go
48 lines (42 loc) · 1005 Bytes
/
issue104_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package mergo_test
import (
"reflect"
"testing"
"dario.cat/mergo"
)
type Record struct {
Data map[string]interface{}
Mapping map[string]string
}
func StructToRecord(in interface{}) *Record {
rec := Record{}
rec.Data = make(map[string]interface{})
rec.Mapping = make(map[string]string)
typ := reflect.TypeOf(in)
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
dbFieldName := field.Tag.Get("db")
if dbFieldName != "" {
rec.Mapping[field.Name] = dbFieldName
}
}
if err := mergo.Map(&rec.Data, in); err != nil {
panic(err)
}
return &rec
}
func TestStructToRecord(t *testing.T) {
type A struct {
Name string `json:"name" db:"name"`
CIDR string `json:"cidr" db:"cidr"`
}
type Record struct {
Data map[string]interface{}
Mapping map[string]string
}
a := A{Name: "David", CIDR: "10.0.0.0/8"}
rec := StructToRecord(a)
if len(rec.Mapping) < 2 {
t.Fatalf("struct to record failed, no mapping, struct missing tags?, rec: %+v, a: %+v ", rec, a)
}
}