|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one or more |
| 2 | +// contributor license agreements. See the NOTICE file distributed with |
| 3 | +// this work for additional information regarding copyright ownership. |
| 4 | +// The ASF licenses this file to You under the Apache License, Version 2.0 |
| 5 | +// (the "License"); you may not use this file except in compliance with |
| 6 | +// the License. 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 | +package types |
| 16 | + |
| 17 | +import ( |
| 18 | + "encoding/json" |
| 19 | + "fmt" |
| 20 | + "time" |
| 21 | +) |
| 22 | + |
| 23 | +// TimeDuration is yet another time.Duration but implements json.Unmarshaler |
| 24 | +// and json.Marshaler, yaml.Unmarshaler and yaml.Marshaler interfaces so one |
| 25 | +// can use "1h", "5s" and etc in their json/yaml configurations. |
| 26 | +// |
| 27 | +// Note the format to represent time is same as time.Duration. |
| 28 | +// See the comments about time.ParseDuration for more details. |
| 29 | +type TimeDuration struct { |
| 30 | + time.Duration `json:",inline"` |
| 31 | +} |
| 32 | + |
| 33 | +func (d *TimeDuration) MarshalJSON() ([]byte, error) { |
| 34 | + return json.Marshal(d.Duration.String()) |
| 35 | +} |
| 36 | + |
| 37 | +func (d *TimeDuration) UnmarshalJSON(data []byte) error { |
| 38 | + var value interface{} |
| 39 | + if err := json.Unmarshal(data, &value); err != nil { |
| 40 | + return err |
| 41 | + } |
| 42 | + switch v := value.(type) { |
| 43 | + case float64: |
| 44 | + d.Duration = time.Duration(v) |
| 45 | + case string: |
| 46 | + dur, err := time.ParseDuration(v) |
| 47 | + if err != nil { |
| 48 | + return err |
| 49 | + } |
| 50 | + d.Duration = dur |
| 51 | + default: |
| 52 | + return fmt.Errorf("unknown type: %T", v) |
| 53 | + } |
| 54 | + return nil |
| 55 | +} |
| 56 | + |
| 57 | +func (d *TimeDuration) MarshalYAML() (interface{}, error) { |
| 58 | + return d.Duration.String(), nil |
| 59 | +} |
| 60 | + |
| 61 | +func (d *TimeDuration) UnmarshalYAML(unmarshal func(interface{}) error) error { |
| 62 | + var s string |
| 63 | + if err := unmarshal(&s); err != nil { |
| 64 | + return err |
| 65 | + } |
| 66 | + dur, err := time.ParseDuration(s) |
| 67 | + if err != nil { |
| 68 | + return err |
| 69 | + } |
| 70 | + d.Duration = dur |
| 71 | + return nil |
| 72 | +} |
0 commit comments