duration.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package v1
  14. import (
  15. "encoding/json"
  16. "time"
  17. )
  18. // Duration is a wrapper around time.Duration which supports correct
  19. // marshaling to YAML and JSON. In particular, it marshals into strings, which
  20. // can be used as map keys in json.
  21. type Duration struct {
  22. time.Duration `protobuf:"varint,1,opt,name=duration,casttype=time.Duration"`
  23. }
  24. // UnmarshalJSON implements the json.Unmarshaller interface.
  25. func (d *Duration) UnmarshalJSON(b []byte) error {
  26. var str string
  27. err := json.Unmarshal(b, &str)
  28. if err != nil {
  29. return err
  30. }
  31. pd, err := time.ParseDuration(str)
  32. if err != nil {
  33. return err
  34. }
  35. d.Duration = pd
  36. return nil
  37. }
  38. // MarshalJSON implements the json.Marshaler interface.
  39. func (d Duration) MarshalJSON() ([]byte, error) {
  40. return json.Marshal(d.Duration.String())
  41. }