forked from labd/commercetools-go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
65 lines (57 loc) · 1.39 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
package commercetools
import (
"net/url"
"reflect"
"regexp"
"time"
"github.com/appscode/go-querystring/query"
mapstructure "github.com/mitchellh/mapstructure"
)
func serializeQueryParams(v interface{}) url.Values {
re := regexp.MustCompile(`([^\]]+)\[([^\]]+)]$`)
values, _ := query.Values(v)
newValues := url.Values{}
for key, values := range values {
newKey := re.ReplaceAllString(key, "$1.$2")
for _, value := range values {
newValues.Add(newKey, value)
}
}
return newValues
}
func toTimeHookFunc() mapstructure.DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if t != reflect.TypeOf(time.Time{}) {
return data, nil
}
switch f.Kind() {
case reflect.String:
return time.Parse(time.RFC3339, data.(string))
case reflect.Float64:
return time.Unix(0, int64(data.(float64))*int64(time.Millisecond)), nil
case reflect.Int64:
return time.Unix(0, data.(int64)*int64(time.Millisecond)), nil
default:
return data, nil
}
// Convert it by parsing
}
}
func decodeStruct(input interface{}, result interface{}) error {
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Metadata: nil,
DecodeHook: mapstructure.ComposeDecodeHookFunc(
toTimeHookFunc()),
Result: result,
})
if err != nil {
return err
}
if err := decoder.Decode(input); err != nil {
return err
}
return err
}