Merge branch '9162-keep-balance'
[arvados.git] / sdk / go / arvados / duration.go
1 package arvados
2
3 import (
4         "encoding/json"
5         "fmt"
6         "time"
7 )
8
9 // Duration is time.Duration but looks like "12s" in JSON, rather than
10 // a number of nanoseconds.
11 type Duration time.Duration
12
13 // UnmarshalJSON implements json.Unmarshaler
14 func (d *Duration) UnmarshalJSON(data []byte) error {
15         if data[0] == '"' {
16                 dur, err := time.ParseDuration(string(data[1 : len(data)-1]))
17                 *d = Duration(dur)
18                 return err
19         }
20         return fmt.Errorf("duration must be given as a string like \"600s\" or \"1h30m\"")
21 }
22
23 // MarshalJSON implements json.Marshaler
24 func (d *Duration) MarshalJSON() ([]byte, error) {
25         return json.Marshal(d.String())
26 }
27
28 // String implements fmt.Stringer
29 func (d Duration) String() string {
30         return time.Duration(d).String()
31 }