Skip to content

Commit

Permalink
Merge pull request #184 from unistack-org/duration
Browse files Browse the repository at this point in the history
util/time: add Marshal/Unmarshal to own Duration
  • Loading branch information
vtolstov authored Feb 13, 2023
2 parents f4d0237 + b07806b commit 3ba8cb7
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
34 changes: 34 additions & 0 deletions util/time/duration.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package time

import (
"encoding/json"
"fmt"
"time"
)
Expand Down Expand Up @@ -46,3 +47,36 @@ func ParseDuration(s string) (time.Duration, error) {

return td, err
}

func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(d).String())
}

func (d *Duration) UnmarshalJSON(b []byte) error {
var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
switch value := v.(type) {
case float64:
*d = Duration(time.Duration(value))
return nil
case string:
dv, err := time.ParseDuration(value)
if err != nil {
return err
}
*d = Duration(dv)
return nil
default:
return fmt.Errorf("invalid duration")
}
}

/*
func (d Duration) MarshalYAML() (interface{}, error) {
return nil, nil
}
func (d Duration) UnmarshalYAML(fn func(interface{}) error) error
*/
27 changes: 27 additions & 0 deletions util/time/duration_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,37 @@
package time

import (
"bytes"
"encoding/json"
"testing"
"time"
)

func TestMarshalJSON(t *testing.T) {
d := Duration(10000000)
buf, err := json.Marshal(d)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(buf, []byte(`"10ms"`)) {
t.Fatalf("invalid duration: %s != %s", buf, `"10ms"`)
}
}

func TestUnmarshalJSON(t *testing.T) {
type str struct {
TTL Duration `json:"ttl"`
}
v := &str{}

err := json.Unmarshal([]byte(`{"ttl":"10ms"}`), v)
if err != nil {
t.Fatal(err)
} else if v.TTL != 10000000 {
t.Fatalf("invalid duration %v != 10000000", v.TTL)
}
}

func TestParseDuration(t *testing.T) {
var td time.Duration
var err error
Expand Down

0 comments on commit 3ba8cb7

Please sign in to comment.