-
Notifications
You must be signed in to change notification settings - Fork 21
/
utils.go
102 lines (89 loc) · 2.14 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package kavenegar
import (
"encoding/json"
"fmt"
"net/url"
"reflect"
"strconv"
"strings"
"time"
)
//ToString ...
func ToString(i interface{}) string {
return strings.Trim(strings.Replace(fmt.Sprint(i), " ", ",", -1), "[]")
}
//ToJson ...
func ToJson(i interface{}) string {
_json, _ := json.Marshal(i)
return string(_json)
}
//ToUnix ...
func ToUnix(t time.Time) string {
return strconv.FormatInt(t.Unix(), 10)
}
//structToUrlValues ...
func structToURLValues(i interface{}) url.Values {
v := url.Values{}
if reflect.ValueOf(i).IsNil() {
return v
}
m := structToMapString(i)
for k, s := range m {
switch {
case len(s) == 1:
v.Set(k, s[0])
case len(s) > 1:
for i := range s {
v.Add(k, s[i])
}
}
}
return v
}
// structToMapString converts struct as map string
func structToMapString(i interface{}) map[string][]string {
ms := map[string][]string{}
iv := reflect.ValueOf(i).Elem()
tp := iv.Type()
for i := 0; i < iv.NumField(); i++ {
if isMap(iv.Field(i)) {
m := iv.Field(i).Interface()
for key, value := range m.(map[string]string) {
ms[key] = []string{value}
}
} else {
k := tp.Field(i).Name
f := iv.Field(i)
ms[k] = valueToString(f)
}
}
return ms
}
func isMap(f reflect.Value) bool {
return reflect.TypeOf(f.Interface()).Kind() == reflect.Map
}
// valueToString converts supported type of f as slice string
func valueToString(f reflect.Value) []string {
var v []string
switch reflect.TypeOf(f.Interface()).Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v = []string{strconv.FormatInt(f.Int(), 10)}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
v = []string{strconv.FormatUint(f.Uint(), 10)}
case reflect.Float32:
v = []string{strconv.FormatFloat(f.Float(), 'f', 4, 32)}
case reflect.Float64:
v = []string{strconv.FormatFloat(f.Float(), 'f', 4, 64)}
case reflect.Bool:
v = []string{strconv.FormatBool(f.Bool())}
case reflect.Slice:
for i := 0; i < f.Len(); i++ {
if s := valueToString(f.Index(i)); len(s) == 1 {
v = append(v, s[0])
}
}
case reflect.String:
v = []string{f.String()}
}
return v
}