-
Notifications
You must be signed in to change notification settings - Fork 0
/
querybuilder.go
92 lines (73 loc) · 1.87 KB
/
querybuilder.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
89
90
91
92
/*
GVK
Copyright (C) 2023-2024 The GVK Devs
GVK is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 3 of the License,
or (at your option) any later version.
GVK is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package gvk
import (
"encoding/json"
"net/url"
"reflect"
"strconv"
)
func toString(v reflect.Value) string {
switch v.Kind() {
case reflect.String:
return v.String()
case reflect.Float64:
return strconv.FormatFloat(v.Float(), 'f', -1, 64)
case reflect.Int, reflect.Int64:
return strconv.FormatInt(v.Int(), 10)
case reflect.Bool:
return strconv.FormatBool(v.Bool())
case reflect.Struct, reflect.Interface, reflect.Slice, reflect.Array:
b, _ := json.Marshal(v.Interface())
return string(b)
default:
return ""
}
}
func scan(i any, v url.Values) url.Values {
e := reflect.ValueOf(i)
if e.Kind() == reflect.Pointer {
e = e.Elem()
}
if e.Kind() == reflect.Invalid {
return v
}
for i := 0; i < e.NumField(); i++ {
fTag := e.Type().Field(i).Tag
// TODO: peer_id = 0 !!! is valid!
if name := fTag.Get("query"); name != "" && !e.Field(i).IsZero() {
v.Set(name, toString(e.Field(i)))
}
}
return v
}
func querify(i any) string {
return scan(i, url.Values{}).Encode()
}
func urlValues(i any) url.Values {
if i == nil {
return nil
}
return scan(i, url.Values{})
}
func addValues(vals url.Values, i any) url.Values {
if i == nil {
return vals
}
if vals == nil {
vals = make(url.Values)
}
return scan(i, vals)
}