timeutil: time.Duration json helper

This commit is contained in:
Ask Bjørn Hansen 2023-07-22 00:10:55 -07:00
parent 03bde25c6d
commit 2a021b453d
2 changed files with 58 additions and 0 deletions

36
timeutil/duration.go Normal file
View File

@ -0,0 +1,36 @@
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")
}
}

22
timeutil/duration_test.go Normal file
View File

@ -0,0 +1,22 @@
package timeutil
import (
"encoding/json"
"testing"
)
func TestDuration(t *testing.T) {
js := []byte(`{"foo": "30s"}`)
foo := struct{ Foo Duration }{}
err := json.Unmarshal(js, &foo)
if err != nil {
t.Fatalf("could not unmarshal %q: %s", js, err)
}
if foo.Foo.Seconds() != 30 {
t.Fatalf("parsed time.Duration wasn't 30 seconds: %s", foo.Foo)
}
}