-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
88 lines (70 loc) · 1.56 KB
/
query.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package fireblocksdk
import (
"fmt"
"net/url"
"reflect"
"strings"
)
type QueryItems []QueryItem
//go:generate stringer -type=EnvEntry
type QueryItem struct {
Key, Value string
}
func (e QueryItem) String() string {
return fmt.Sprintf("%s = %s", e.Key, e.Value)
}
// BuildQuery uses `env` and `envDefault` as tag to bind config to viper bindings
// Example: `env:"USERNAME" envDefault:"admin"`
func BuildQuery(in any) QueryItems {
if in == nil || reflect.ValueOf(in).IsNil() {
return nil
}
var vars QueryItems
var t = reflect.TypeOf(in)
var kind = t.Kind()
if kind == reflect.Ptr {
t = t.Elem()
kind = t.Kind()
}
if kind == reflect.Struct {
iterateStructFields(t, in, &vars)
}
return vars
}
func (items QueryItems) URLValues() url.Values {
values := make(url.Values, len(items))
for _, val := range items {
if val.Value != "" {
values.Add(normalize(val.Key, val.Value))
}
}
return values
}
func normalize(key, value string) (string, string) {
substrings := strings.Split(key, ",")
return substrings[0], value
}
func iterateStructFields(t reflect.Type, v any, vars *QueryItems) {
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
for i := 0; i < t.NumField(); i++ {
var field = t.Field(i)
tag := field.Tag.Get("json")
value := val.Field(i)
kind := value.Kind()
var vv any
if kind == reflect.Ptr {
value = value.Elem()
vv = value.Interface()
} else {
vv = value.Interface()
}
entry := QueryItem{
Key: tag,
Value: fmt.Sprintf("%v", vv),
}
*vars = append(*vars, entry)
}
}