-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreflect.go
More file actions
113 lines (98 loc) · 2.1 KB
/
reflect.go
File metadata and controls
113 lines (98 loc) · 2.1 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package yc_lockbox_unpack
import (
"encoding"
"fmt"
"reflect"
"strconv"
"strings"
)
func unpackText(field reflect.Value, value string) error {
if field.Kind() == reflect.Ptr {
switch {
case value == "":
return nil
case field.IsNil():
field.Set(reflect.New(field.Type().Elem()))
}
field = field.Elem()
}
if !field.CanInterface() {
return nil
}
fieldIf := field.Interface()
switch fieldIf.(type) {
case bool:
value = strings.TrimSpace(value)
b, err := strconv.ParseBool(value)
if err != nil {
return err
}
field.SetBool(b)
case int, int8, int16, int32, int64:
value = strings.TrimSpace(value)
i, err := strconv.ParseInt(value, 0, 64)
if err != nil {
return err
}
field.SetInt(i)
case uint, uint8, uint16, uint32, uint64:
value = strings.TrimSpace(value)
u, err := strconv.ParseUint(value, 0, 64)
if err != nil {
return err
}
field.SetUint(u)
case float32, float64:
value = strings.TrimSpace(value)
f, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
field.SetFloat(f)
case string:
field.SetString(value)
case []byte:
field.SetBytes([]byte(value))
default:
for field.CanAddr() {
field = field.Addr()
}
umarshaller, ok := field.Interface().(encoding.TextUnmarshaler)
if ok {
return umarshaller.UnmarshalText([]byte(value))
}
return fmt.Errorf("don't know how to parse type: %s", field.Type())
}
return nil
}
func unpackBinary(field reflect.Value, value []byte) error {
if field.Kind() == reflect.Ptr {
switch {
case value == nil:
return nil
case field.IsNil():
field.Set(reflect.New(field.Type().Elem()))
}
field = field.Elem()
}
if !field.CanInterface() {
return nil
}
fieldIf := field.Interface()
switch fieldIf.(type) {
case string:
field.SetString(string(value))
case []byte:
field.SetBytes(value)
default:
for field.CanAddr() {
field = field.Addr()
}
umarshaller, ok := field.Interface().(encoding.BinaryUnmarshaler)
if ok {
return umarshaller.UnmarshalBinary(value)
}
return fmt.Errorf("don't know how to parse type: %s", field.Type())
}
return nil
}