-
Notifications
You must be signed in to change notification settings - Fork 18
/
decode.go
45 lines (38 loc) · 916 Bytes
/
decode.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
package runscope
import (
"github.com/mitchellh/mapstructure"
"reflect"
"time"
)
func floatToTimeDurationHookFunc() mapstructure.DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() != reflect.Float64 {
return data, nil
}
if t != reflect.TypeOf(time.Now()) {
return data, nil
}
// Convert it by parsing
rawValue := data.(float64)
seconds := int64(rawValue)
nanoSeconds := int64((rawValue - float64(int64(rawValue))) * 1e9)
return time.Unix(seconds, nanoSeconds), nil
}
}
func decode(result interface{}, response interface{}) error {
config := &mapstructure.DecoderConfig{
Metadata: nil,
Result: result,
TagName: "json",
DecodeHook: floatToTimeDurationHookFunc(),
}
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
panic(err)
}
err = decoder.Decode(response)
return err
}