-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
48 lines (45 loc) · 1.06 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
package kopenai
import (
"encoding/json"
"fmt"
"net/url"
"reflect"
"strconv"
)
func PrettyPrint(obj interface{}) {
b, err := json.MarshalIndent(obj, "", " ")
if err != nil {
fmt.Println(err)
}
fmt.Print(string(b))
}
func StructToUrlValues(i interface{}) (values url.Values) {
values = url.Values{}
iVal := reflect.ValueOf(i).Elem()
typ := iVal.Type()
for i := 0; i < iVal.NumField(); i++ {
f := iVal.Field(i)
// You ca use tags here...
// tag := typ.Field(i).Tag.Get("tagname")
// Convert each type into a string for the url.Values string map
var v string
switch f.Interface().(type) {
case int, int8, int16, int32, int64:
v = strconv.FormatInt(f.Int(), 10)
case uint, uint8, uint16, uint32, uint64:
v = strconv.FormatUint(f.Uint(), 10)
case float32:
v = strconv.FormatFloat(f.Float(), 'f', 4, 32)
case float64:
v = strconv.FormatFloat(f.Float(), 'f', 4, 64)
case []byte:
v = string(f.Bytes())
case string:
v = f.String()
case fmt.Stringer:
v = f.String()
}
values.Set(typ.Field(i).Tag.Get("json"), v)
}
return
}