Skip to content

Commit

Permalink
fix: Implement YAML en-/decoder (fixes #223)
Browse files Browse the repository at this point in the history
  • Loading branch information
robinbraemer committed Jul 23, 2023
1 parent 59afe39 commit b034584
Showing 1 changed file with 41 additions and 10 deletions.
51 changes: 41 additions & 10 deletions pkg/util/configutil/duration.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"encoding/json"
"fmt"
"time"

"gopkg.in/yaml.v3"
)

// Duration is a configuration duration.
Expand All @@ -13,28 +15,57 @@ import (
// - int64 and float64 are interpreted as seconds.
type Duration time.Duration

// Make sure Duration implements the interfaces at compile time.
var (
_ yaml.Marshaler = (*Duration)(nil)
_ yaml.Unmarshaler = (*Duration)(nil)

_ json.Marshaler = (*Duration)(nil)
_ json.Unmarshaler = (*Duration)(nil)
)

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

func (d *Duration) UnmarshalJSON(data []byte) error {
var a any
if err := json.Unmarshal(data, &a); err != nil {
return err
}
dur, err := decode(a)
if err != nil {
return err
}
*d = Duration(dur)
return nil
}

func (d *Duration) MarshalYAML() (interface{}, error) {
return time.Duration(*d).String(), nil
}
func (d *Duration) UnmarshalYAML(value *yaml.Node) error {
var a any
err := value.Decode(&a)
if err != nil {
return err
}
dur, err := decode(a)
if err != nil {
return err
}
*d = Duration(dur)
return nil
}

func decode(a any) (time.Duration, error) {
switch v := a.(type) {
case string:
dur, err := time.ParseDuration(v)
if err != nil {
return err
}
*d = Duration(dur)
return time.ParseDuration(v)
case float64:
*d = Duration(time.Duration(v) * time.Second)
return time.Duration(v) * time.Second, nil
case int64:
*d = Duration(time.Duration(v) * time.Second)
return time.Duration(v) * time.Second, nil
default:
return fmt.Errorf("invalid duration type %T: %v", v, v)
return 0, fmt.Errorf("invalid duration type %T: %v", v, v)
}
return nil
}

0 comments on commit b034584

Please sign in to comment.