This repository has been archived by the owner on Sep 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathutils.go
84 lines (71 loc) · 1.74 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package crunchyroll
import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"reflect"
"strings"
)
func decodeMapToStruct(m interface{}, s interface{}) error {
jsonBody, err := json.Marshal(m)
if err != nil {
return err
}
return json.Unmarshal(jsonBody, s)
}
func regexGroups(parsed [][]string, subexpNames ...string) map[string]string {
groups := map[string]string{}
for _, match := range parsed {
for i, content := range match {
if subexpName := subexpNames[i]; subexpName != "" {
groups[subexpName] = content
}
}
}
return groups
}
func encodeStructToQueryValues(s interface{}) (string, error) {
values := make(url.Values)
v := reflect.ValueOf(s)
for i := 0; i < v.Type().NumField(); i++ {
// don't include parameters with default or without values in the query to avoid corruption of the API response.
switch v.Field(i).Kind() {
case reflect.Slice, reflect.String:
if v.Field(i).Len() == 0 {
continue
}
case reflect.Bool:
if !v.Field(i).Bool() {
continue
}
case reflect.Uint:
if v.Field(i).Uint() == 0 {
continue
}
}
key := v.Type().Field(i).Tag.Get("param")
var val string
if v.Field(i).Kind() == reflect.Slice {
var items []string
for _, i := range v.Field(i).Interface().([]string) {
items = append(items, i)
}
val = strings.Join(items, ",")
} else {
val = fmt.Sprint(v.Field(i).Interface())
}
values.Add(key, val)
}
return values.Encode(), nil
}
func structDefaults[T any](defaultStruct T, customStruct T) (T, error) {
rawDefaultStruct, err := json.Marshal(defaultStruct)
if err != nil {
return *new(T), err
}
if err = json.NewDecoder(bytes.NewBuffer(rawDefaultStruct)).Decode(&customStruct); err != nil {
return *new(T), err
}
return customStruct, nil
}