-
Notifications
You must be signed in to change notification settings - Fork 1
/
mapper.go
48 lines (38 loc) · 1.22 KB
/
mapper.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 structmapper
import "github.com/hashicorp/go-multierror"
// Mapper provides the mapping logic
type Mapper struct {
tagName string
}
// ToStruct takes a source map[string]interface{} and maps its values onto a target struct.
func (mapper *Mapper) ToStruct(source map[string]interface{}, target interface{}) error {
return mapper.toStruct(source, target)
}
// ToMap takes a source struct and maps its values onto a map[string]interface{}, which is then returned.
func (mapper *Mapper) ToMap(source interface{}) (map[string]interface{}, error) {
return mapper.toMap(source)
}
// NewMapper initializes a new mapper instance.
// Optionally Mapper options may be passed to this function
func NewMapper(options ...Option) (*Mapper, error) {
sm := &Mapper{}
var err error
// Apply default options first
for _, opt := range defaultOptions {
if optErr := opt(sm); optErr != nil {
// Panic if default option could not be applied
panic(optErr)
}
}
// ... and passed options afterwards.
// This way the passed options override the default options
for _, opt := range options {
if optErr := opt(sm); optErr != nil {
err = multierror.Append(err, optErr)
}
}
if err != nil {
return nil, err
}
return sm, nil
}