4
0

duration.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. // NewDuration parses a duration string and returns a Duration type or an error
  12. // if the given string is not a duration.
  13. func NewDuration(s string) (*Duration, error) {
  14. d, err := time.ParseDuration(s)
  15. if err != nil {
  16. return nil, errors.Wrapf(err, "error parsing %s as duration", s)
  17. }
  18. return &Duration{Duration: d}, nil
  19. }
  20. // MarshalJSON parses a duration string and sets it to the duration.
  21. //
  22. // A duration string is a possibly signed sequence of decimal numbers, each with
  23. // optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
  24. // Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
  25. func (d *Duration) MarshalJSON() ([]byte, error) {
  26. return json.Marshal(d.Duration.String())
  27. }
  28. // UnmarshalJSON parses a duration string and sets it to the duration.
  29. //
  30. // A duration string is a possibly signed sequence of decimal numbers, each with
  31. // optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
  32. // Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
  33. func (d *Duration) UnmarshalJSON(data []byte) (err error) {
  34. var (
  35. s string
  36. dd time.Duration
  37. )
  38. if d == nil {
  39. return errors.New("duration cannot be nil")
  40. }
  41. if err = json.Unmarshal(data, &s); err != nil {
  42. return errors.Wrapf(err, "error unmarshaling %s", data)
  43. }
  44. if dd, err = time.ParseDuration(s); err != nil {
  45. return errors.Wrapf(err, "error parsing %s as duration", s)
  46. }
  47. d.Duration = dd
  48. return
  49. }
  50. // Value returns 0 if the duration is null, the inner duration otherwise.
  51. func (d *Duration) Value() time.Duration {
  52. if d == nil {
  53. return 0
  54. }
  55. return d.Duration
  56. }