-
Notifications
You must be signed in to change notification settings - Fork 82
/
timejson.go
41 lines (36 loc) · 951 Bytes
/
timejson.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
// Package timejson extends time methods with marshal/unmarshal for json
package timejson
import (
"encoding/json"
"errors"
"time"
)
var errInvalid = errors.New("invalid duration")
// Duration is an alias to time.Duration
// Implementation taken from https://stackoverflow.com/questions/48050945/how-to-unmarshal-json-into-durations
type Duration time.Duration
// MarshalJSON converts a duration to json
func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(d).String())
}
// UnmarshalJSON converts json to a duration
func (d *Duration) UnmarshalJSON(b []byte) error {
var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
switch value := v.(type) {
case float64:
*d = Duration(time.Duration(value))
return nil
case string:
timeDur, err := time.ParseDuration(value)
if err != nil {
return err
}
*d = Duration(timeDur)
return nil
default:
return errInvalid
}
}