Skip to content
This repository was archived by the owner on Mar 9, 2022. It is now read-only.

Commit 82ef273

Browse files
committed
feat: add and use a duration helper type
1 parent 8830cdc commit 82ef273

File tree

3 files changed

+55
-1
lines changed

3 files changed

+55
-1
lines changed

autonat.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -75,5 +75,7 @@ type AutoNATThrottleConfig struct {
7575

7676
// Interval specifies how frequently this node should reset the
7777
// global/peer dialback limits.
78-
Interval string
78+
//
79+
// When unset, this defaults to 1 minute.
80+
Interval Duration `json:",omitempty"`
7981
}

types.go

+20
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package config
22

33
import (
44
"encoding/json"
5+
"time"
56
)
67

78
// 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) {
3940

4041
var _ json.Unmarshaler = (*Strings)(nil)
4142
var _ json.Marshaler = (*Strings)(nil)
43+
44+
// Duration wraps time.Duration to provide json serialization and deserialization.
45+
//
46+
// NOTE: the zero value encodes to an empty string.
47+
type Duration time.Duration
48+
49+
func (d *Duration) UnmarshalText(text []byte) error {
50+
dur, err := time.ParseDuration(string(text))
51+
*d = Duration(dur)
52+
return err
53+
}
54+
55+
func (d Duration) MarshalText() ([]byte, error) {
56+
return []byte(time.Duration(d).String()), nil
57+
}
58+
59+
func (d Duration) String() string {
60+
return time.Duration(d).String()
61+
}

types_test.go

+32
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,40 @@ package config
33
import (
44
"encoding/json"
55
"testing"
6+
"time"
67
)
78

9+
func TestDuration(t *testing.T) {
10+
out, err := json.Marshal(Duration(time.Second))
11+
if err != nil {
12+
t.Fatal(err)
13+
14+
}
15+
expected := "\"1s\""
16+
if string(out) != expected {
17+
t.Fatalf("expected %s, got %s", expected, string(out))
18+
}
19+
var d Duration
20+
err = json.Unmarshal(out, &d)
21+
if err != nil {
22+
t.Fatal(err)
23+
}
24+
if time.Duration(d) != time.Second {
25+
t.Fatal("expected a second")
26+
}
27+
type Foo struct {
28+
D Duration `json:",omitempty"`
29+
}
30+
out, err = json.Marshal(new(Foo))
31+
if err != nil {
32+
t.Fatal(err)
33+
}
34+
expected = "{}"
35+
if string(out) != expected {
36+
t.Fatal("expected omitempty to omit the duration")
37+
}
38+
}
39+
840
func TestOneStrings(t *testing.T) {
941
out, err := json.Marshal(Strings{"one"})
1042
if err != nil {

0 commit comments

Comments
 (0)