diff --git a/config/autonat.go b/config/autonat.go index 05009ffc5dcb..a1a3f699cdac 100644 --- a/config/autonat.go +++ b/config/autonat.go @@ -75,5 +75,7 @@ type AutoNATThrottleConfig struct { // Interval specifies how frequently this node should reset the // global/peer dialback limits. - Interval string + // + // When unset, this defaults to 1 minute. + Interval Duration `json:",omitempty"` } diff --git a/config/types.go b/config/types.go index 58451c68f12d..90363e30dc42 100644 --- a/config/types.go +++ b/config/types.go @@ -2,6 +2,7 @@ package config import ( "encoding/json" + "time" ) // Strings is a helper type that (un)marshals a single string to/from a single @@ -39,3 +40,22 @@ func (o Strings) MarshalJSON() ([]byte, error) { var _ json.Unmarshaler = (*Strings)(nil) var _ json.Marshaler = (*Strings)(nil) + +// Duration wraps time.Duration to provide json serialization and deserialization. +// +// NOTE: the zero value encodes to an empty string. +type Duration time.Duration + +func (d *Duration) UnmarshalText(text []byte) error { + dur, err := time.ParseDuration(string(text)) + *d = Duration(dur) + return err +} + +func (d Duration) MarshalText() ([]byte, error) { + return []byte(time.Duration(d).String()), nil +} + +func (d Duration) String() string { + return time.Duration(d).String() +} diff --git a/config/types_test.go b/config/types_test.go index 7523962ae839..295ce9229950 100644 --- a/config/types_test.go +++ b/config/types_test.go @@ -3,8 +3,40 @@ package config import ( "encoding/json" "testing" + "time" ) +func TestDuration(t *testing.T) { + out, err := json.Marshal(Duration(time.Second)) + if err != nil { + t.Fatal(err) + + } + expected := "\"1s\"" + if string(out) != expected { + t.Fatalf("expected %s, got %s", expected, string(out)) + } + var d Duration + err = json.Unmarshal(out, &d) + if err != nil { + t.Fatal(err) + } + if time.Duration(d) != time.Second { + t.Fatal("expected a second") + } + type Foo struct { + D Duration `json:",omitempty"` + } + out, err = json.Marshal(new(Foo)) + if err != nil { + t.Fatal(err) + } + expected = "{}" + if string(out) != expected { + t.Fatal("expected omitempty to omit the duration") + } +} + func TestOneStrings(t *testing.T) { out, err := json.Marshal(Strings{"one"}) if err != nil {