Zack Williams | e940c7a | 2019-08-21 14:25:39 -0700 | [diff] [blame] | 1 | /* |
| 2 | Copyright 2014 The Kubernetes Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package v1 |
| 18 | |
| 19 | import ( |
| 20 | "encoding/json" |
| 21 | "time" |
| 22 | ) |
| 23 | |
| 24 | // Duration is a wrapper around time.Duration which supports correct |
| 25 | // marshaling to YAML and JSON. In particular, it marshals into strings, which |
| 26 | // can be used as map keys in json. |
| 27 | type Duration struct { |
| 28 | time.Duration `protobuf:"varint,1,opt,name=duration,casttype=time.Duration"` |
| 29 | } |
| 30 | |
| 31 | // UnmarshalJSON implements the json.Unmarshaller interface. |
| 32 | func (d *Duration) UnmarshalJSON(b []byte) error { |
| 33 | var str string |
| 34 | err := json.Unmarshal(b, &str) |
| 35 | if err != nil { |
| 36 | return err |
| 37 | } |
| 38 | |
| 39 | pd, err := time.ParseDuration(str) |
| 40 | if err != nil { |
| 41 | return err |
| 42 | } |
| 43 | d.Duration = pd |
| 44 | return nil |
| 45 | } |
| 46 | |
| 47 | // MarshalJSON implements the json.Marshaler interface. |
| 48 | func (d Duration) MarshalJSON() ([]byte, error) { |
| 49 | return json.Marshal(d.Duration.String()) |
| 50 | } |
David Bainbridge | 8697152 | 2019-09-26 22:09:39 +0000 | [diff] [blame] | 51 | |
| 52 | // OpenAPISchemaType is used by the kube-openapi generator when constructing |
| 53 | // the OpenAPI spec of this type. |
| 54 | // |
| 55 | // See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators |
| 56 | func (_ Duration) OpenAPISchemaType() []string { return []string{"string"} } |
| 57 | |
| 58 | // OpenAPISchemaFormat is used by the kube-openapi generator when constructing |
| 59 | // the OpenAPI spec of this type. |
| 60 | func (_ Duration) OpenAPISchemaFormat() string { return "" } |