github.com/mailgun/holster/v4@v4.20.0/clock/duration.go (about) 1 package clock 2 3 import ( 4 "encoding/json" 5 6 "github.com/mailgun/holster/v4/errors" 7 ) 8 9 type DurationJSON struct { 10 Duration Duration 11 } 12 13 func NewDurationJSON(v interface{}) (DurationJSON, error) { 14 switch v := v.(type) { 15 case Duration: 16 return DurationJSON{Duration: v}, nil 17 case float64: 18 return DurationJSON{Duration: Duration(v)}, nil 19 case int64: 20 return DurationJSON{Duration: Duration(v)}, nil 21 case int: 22 return DurationJSON{Duration: Duration(v)}, nil 23 case []byte: 24 duration, err := ParseDuration(string(v)) 25 if err != nil { 26 return DurationJSON{}, errors.Wrap(err, "while parsing []byte") 27 } 28 return DurationJSON{Duration: duration}, nil 29 case string: 30 duration, err := ParseDuration(v) 31 if err != nil { 32 return DurationJSON{}, errors.Wrap(err, "while parsing string") 33 } 34 return DurationJSON{Duration: duration}, nil 35 default: 36 return DurationJSON{}, errors.Errorf("bad type %T", v) 37 } 38 } 39 40 func NewDurationJSONOrPanic(v interface{}) DurationJSON { 41 d, err := NewDurationJSON(v) 42 if err != nil { 43 panic(err) 44 } 45 return d 46 } 47 48 func (d DurationJSON) MarshalJSON() ([]byte, error) { 49 return json.Marshal(d.Duration.String()) 50 } 51 52 func (d *DurationJSON) UnmarshalJSON(b []byte) error { 53 var v interface{} 54 55 err := json.Unmarshal(b, &v) 56 if err != nil { 57 return err 58 } 59 60 *d, err = NewDurationJSON(v) 61 return err 62 } 63 64 func (d DurationJSON) String() string { 65 return d.Duration.String() 66 }