common/timeutil/duration.go

37 lines
622 B
Go
Raw Normal View History

2023-07-22 07:10:55 +00:00
package timeutil
import (
"encoding/json"
"errors"
"time"
)
type Duration struct {
time.Duration
}
func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(d.Duration).String())
}
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:
tmp, err := time.ParseDuration(value)
if err != nil {
return err
}
*d = Duration{tmp}
return nil
default:
return errors.New("invalid duration")
}
}