-
Notifications
You must be signed in to change notification settings - Fork 1
/
data.go
88 lines (70 loc) · 1.85 KB
/
data.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package groudon
import (
"github.com/mitchellh/mapstructure"
"encoding/json"
"fmt"
"io"
)
var (
ErrInvalidTyping = fmt.Errorf("json body types do not match expected")
ErrNilBody = fmt.Errorf("body reader is nil")
)
type Fillable interface {
Validators() map[string]func(interface{}) (bool, error)
Defaults() map[string]interface{}
}
func withDefaults(data, defaults map[string]interface{}) (populated map[string]interface{}) {
populated = data
var key string
var it interface{}
for key, it = range defaults {
if populated[key] == nil {
populated[key] = it
}
}
return
}
func validateValues(data map[string]interface{}, validators map[string]func(interface{}) (bool, error)) (valid bool, err error) {
var key string
var validator func(interface{}) (bool, error)
for key, validator = range validators {
if valid, err = validator(data[key]); !valid || err != nil {
break
}
}
return
}
func encodeBody(data map[string]interface{}, target Fillable) (err error) {
var config mapstructure.DecoderConfig = mapstructure.DecoderConfig{
Metadata: nil,
TagName: "json",
Result: target,
}
var decoder *mapstructure.Decoder
if decoder, err = mapstructure.NewDecoder(&config); err == nil {
err = decoder.Decode(data)
}
return
}
func SerializeBody(reader io.Reader, target Fillable) (internal, external error) {
if reader == nil {
external = ErrNilBody
return
}
var closable bool
if _, closable = reader.(io.Closer); closable {
defer reader.(io.Closer).Close()
}
var data map[string]interface{}
if external = json.NewDecoder(reader).Decode(&data); external != nil {
return
}
data = withDefaults(data, target.Defaults())
var valid bool
if valid, internal = validateValues(data, target.Validators()); !valid || internal != nil {
external = ErrInvalidTyping
return
}
internal = encodeBody(data, target)
return
}