duration.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package provisioner
  2. import (
  3. "encoding/json"
  4. "time"
  5. "github.com/pkg/errors"
  6. )
  7. // Duration is a wrapper around Time.Duration to aid with marshal/unmarshal.
  8. type Duration struct {
  9. time.Duration
  10. }
  11. // MarshalJSON parses a duration string and sets it to the duration.
  12. //
  13. // A duration string is a possibly signed sequence of decimal numbers, each with
  14. // optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
  15. // Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
  16. func (d *Duration) MarshalJSON() ([]byte, error) {
  17. return json.Marshal(d.Duration.String())
  18. }
  19. // UnmarshalJSON parses a duration string and sets it to the duration.
  20. //
  21. // A duration string is a possibly signed sequence of decimal numbers, each with
  22. // optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
  23. // Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
  24. func (d *Duration) UnmarshalJSON(data []byte) (err error) {
  25. var (
  26. s string
  27. _d time.Duration
  28. )
  29. if d == nil {
  30. return errors.New("duration cannot be nil")
  31. }
  32. if err = json.Unmarshal(data, &s); err != nil {
  33. return errors.Wrapf(err, "error unmarshaling %s", data)
  34. }
  35. if _d, err = time.ParseDuration(s); err != nil {
  36. return errors.Wrapf(err, "error parsing %s as duration", s)
  37. }
  38. d.Duration = _d
  39. return
  40. }