-
Notifications
You must be signed in to change notification settings - Fork 0
/
mapper_extended.go
63 lines (53 loc) · 1.75 KB
/
mapper_extended.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
package structure
import (
"encoding"
"errors"
"fmt"
"reflect"
"time"
)
func init() {
registerMapper(stringType, reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem(), string2TextUnmarshalerMapper)
registerMapper(stringType, reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem(), string2BinaryUnmarshalerMapper)
registerMapper(stringType, reflect.TypeOf((*time.Duration)(nil)).Elem(), string2durationMapper)
}
func string2TextUnmarshalerMapper(from reflect.Value, to reflect.Value, _ *Option) error {
textUnmarshaler, ok := to.Interface().(encoding.TextUnmarshaler)
if !ok {
if to.CanAddr() {
textUnmarshaler, ok = to.Addr().Interface().(encoding.TextUnmarshaler)
}
}
if ok {
err := textUnmarshaler.UnmarshalText([]byte(from.String()))
if err != nil {
return errors.New(fmt.Sprintf("unable to unmarshal text: %v", err))
}
return nil
}
return errors.New(fmt.Sprintf("type %s could not convert to TextUnmarshaler", to.Type()))
}
func string2BinaryUnmarshalerMapper(from reflect.Value, to reflect.Value, _ *Option) error {
binaryUnmarshaler, ok := to.Interface().(encoding.BinaryUnmarshaler)
if !ok {
if to.CanAddr() {
binaryUnmarshaler, ok = to.Addr().Interface().(encoding.BinaryUnmarshaler)
}
}
if ok {
err := binaryUnmarshaler.UnmarshalBinary([]byte(from.String()))
if err != nil {
return errors.New(fmt.Sprintf("unable to unmarshal binary: %v", err))
}
return nil
}
return errors.New(fmt.Sprintf("type %s could not convert to BinaryUnmarshaler", to.Type()))
}
func string2durationMapper(from reflect.Value, to reflect.Value, _ *Option) error {
s, err := time.ParseDuration(from.String())
if err != nil {
return errors.New(fmt.Sprintf("unable to parse duration: %v", err))
}
to.Set(reflect.ValueOf(s))
return nil
}