-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode_attributes.go
69 lines (56 loc) · 1.21 KB
/
decode_attributes.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package jsonapi
import (
"encoding/json"
"reflect"
"strings"
)
type DecodeField struct {
Value reflect.Value
OmitEmpty bool
}
type DecodeAttributes struct {
d Decodable
}
func NewDecodeAttributes(d Decodable) DecodeAttributes {
return DecodeAttributes{d}
}
func (da DecodeAttributes) UnmarshalJSON(data []byte) error {
var attributes map[string]json.RawMessage
err := json.Unmarshal(data, &attributes)
if err != nil {
return err
}
dValue := reflect.ValueOf(da.d).Elem()
dType := reflect.TypeOf(da.d).Elem()
fieldMap := map[string]DecodeField{}
for i := 0; i < dValue.NumField(); i++ {
fieldStruct := dType.Field(i)
fieldValue := dValue.Field(i)
tag, ok := fieldStruct.Tag.Lookup("jsonapi")
if !ok {
continue
}
parts := strings.Split(tag, ",")
omitEmpty := false
for _, part := range parts {
if part == "omitempty" {
omitEmpty = true
}
}
fieldMap[parts[0]] = DecodeField{
Value: fieldValue,
OmitEmpty: omitEmpty,
}
}
for k, v := range attributes {
field, ok := fieldMap[k]
if !ok || !field.Value.CanAddr() {
continue
}
addr := field.Value.Addr().Interface()
if err := json.Unmarshal(v, addr); err != nil {
return err
}
}
return nil
}