-
Notifications
You must be signed in to change notification settings - Fork 6
/
tag.go
67 lines (53 loc) · 1.63 KB
/
tag.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
package fetch
import (
"fmt"
"reflect"
"github.com/tidwall/gjson"
)
// DataSource defines the interface for loading data from a data source.
type DataSource interface {
Get(key string) string
}
func decodeWithTagFromDataSource(ptr interface{}, tagName string, dataSource gjson.Result) error {
t := reflect.TypeOf(ptr).Elem()
v := reflect.ValueOf(ptr).Elem()
for i := 0; i < t.NumField(); i++ {
typ := t.Field(i)
val := v.Field(i)
kind := val.Kind()
tagValueName := typ.Tag.Get(tagName)
tabValueDfeault := typ.Tag.Get("default")
tagValueRequired := typ.Tag.Get("required")
switch kind {
case reflect.String:
tagValue := dataSource.Get(tagValueName).String()
if tagValue == "" && tabValueDfeault != "" {
tagValue = tabValueDfeault
}
if tagValueRequired == "true" && tagValue == "" {
return fmt.Errorf("%s is required", tagValueName)
}
val.SetString(tagValue)
case reflect.Bool:
tagValue := dataSource.Get(tagValueName).Bool()
val.SetBool(tagValue)
case reflect.Int, reflect.Int64:
tagValue := dataSource.Get(tagValueName).Int()
if tagValueRequired == "true" && tagValue == 0 {
return fmt.Errorf("%s is required", tagValueName)
}
val.SetInt(tagValue)
case reflect.Float64:
tagValue := dataSource.Get(tagValueName).Float()
if tagValueRequired == "true" && tagValue == 0.0 {
return fmt.Errorf("%s is required", tagValueName)
}
val.SetFloat(tagValue)
}
}
return nil
}
// Decode decodes the given struct pointer from the environment.
func decode(ptr interface{}, response *Response) error {
return decodeWithTagFromDataSource(ptr, "alias", response.Value())
}