-
Notifications
You must be signed in to change notification settings - Fork 0
/
gobind.go
63 lines (51 loc) · 1.22 KB
/
gobind.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 gobind
import (
"errors"
"fmt"
"reflect"
"strconv"
)
func getArg(index string, args ...interface{}) (interface{}, error) {
i, err := strconv.ParseInt(index, 10, 64)
if err != nil {
return nil, err
}
if int64(len(args)) <= i {
return nil, fmt.Errorf("invalid args number, want tag %d, but args number is only %d", i, len(args))
}
return args[i], nil
}
func Bind(target interface{}, args ...interface{}) error {
if len(args) == 0 {
return errors.New("invalid args")
}
v := reflect.ValueOf(target).Elem()
// if !v.CanSet() {
// return errors.New("target should be passed with a pointer")
// }
t := v.Type()
for i := 0; i < v.NumField(); i++ {
tag := t.Field(i).Tag.Get("tag")
obj, _ := getArg(tag, args...)
field := v.Field(i)
objValue := reflect.ValueOf(obj)
val := objValue.FieldByName(t.Field(i).Name)
copyValue(field, val)
}
return nil
}
func copyValue(dest reflect.Value, src reflect.Value) error {
if dest.Kind() != dest.Kind() {
return errors.New("wrong reflect Kind")
}
if !dest.CanSet() {
return errors.New("target can't set...")
}
switch dest.Kind() {
case reflect.String:
dest.SetString(src.String())
default:
return errors.New("unsupport reflect kind..")
}
return nil
}