mirror of
https://github.com/ipfs/kubo.git
synced 2026-02-24 03:47:45 +08:00
go-ipfs-config: feat: add and use a duration helper type
This commit is contained in:
parent
3c6a974ae4
commit
25a96cfb1b
@ -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"`
|
||||
}
|
||||
|
||||
@ -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()
|
||||
}
|
||||
|
||||
@ -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 {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user