go-ipfs-config: feat: add and use a duration helper type
Steven Allen committed
Apr 14, 2020 at 19:55 UTC
25a96cfb1bdcfcd6ee0090a28bbd5df051f67345
3 files changed
+55
-1
config/autonat.go
+3
-1
@@ -75,5 +75,7 @@ type AutoNATThrottleConfig struct {
75
76
// Interval specifies how frequently this node should reset the
77
// global/peer dialback limits.
78
- Interval string
78
+ //
79
+ // When unset, this defaults to 1 minute.
80
+ Interval Duration `json:",omitempty"`
81
}
config/types.go
+20
@@ -2,6 +2,7 @@ package config
2
3
import (
4
"encoding/json"
5
+ "time"
6
)
7
8
// 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) {
40
41
var _ json.Unmarshaler = (*Strings)(nil)
42
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
+}
config/types_test.go
+32
@@ -3,8 +3,40 @@ package config
3
import (
4
"encoding/json"
5
"testing"
6
+ "time"
7
)
8
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
+
40
func TestOneStrings(t *testing.T) {
41
out, err := json.Marshal(Strings{"one"})
42
if err != nil {