Skip to content

Commit

Permalink
go-ipfs-config: Merge pull request ipfs#76 from ipfs/feat/duration-type
Browse files Browse the repository at this point in the history
feat: add and use a duration helper type
  • Loading branch information
Stebalien authored Apr 15, 2020
2 parents c79826a + b2a03d7 commit bb90d66
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
4 changes: 3 additions & 1 deletion config/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 config/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 config/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

0 comments on commit bb90d66

Please sign in to comment.