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

feat: add and use a duration helper type #76

Merged
merged 1 commit into from
Apr 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion autonat.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
20 changes: 20 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
}
32 changes: 32 additions & 0 deletions types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down