-
Notifications
You must be signed in to change notification settings - Fork 44
/
utils.go
66 lines (53 loc) · 1.48 KB
/
utils.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
package lib
import (
"errors"
"net/url"
"reflect"
"strconv"
)
func MustParseURL(rawURL string) *url.URL {
u, err := url.Parse(rawURL)
if err != nil {
panic(err)
}
return u
}
type QueryParam struct {
Key string
Value string
}
func GenerateQueryParamsFromStruct[T interface{}](queryParamsStruct T) ([]QueryParam, error) {
var queryParamList []QueryParam = make([]QueryParam, 0)
values := reflect.ValueOf(queryParamsStruct)
if values.Kind() != reflect.Struct {
return nil, errors.New("queryParamsStruct must be a struct. Make sure you are not passing a pointer to struct")
}
types := values.Type()
for i := 0; i < values.NumField(); i++ {
field := values.Field(i)
if !field.IsZero() {
// Check if the field has a queryKey tag and use that as the key for the query param
key := types.Field(i).Tag.Get("queryKey")
if key == "" {
key = types.Field(i).Name
}
// Check if the field is a string, bool or int and convert it to string
var value string
switch field.Kind() {
case reflect.String:
value = field.Interface().(string)
case reflect.Bool:
value = strconv.FormatBool(field.Interface().(bool))
case reflect.Int:
value = strconv.FormatInt(int64(field.Interface().(int)), 10)
default:
return nil, errors.New("unsupported type in struct field. Supported types are: string, bool and int")
}
queryParamList = append(queryParamList, QueryParam{
Key: key,
Value: value,
})
}
}
return queryParamList, nil
}