David K. Bainbridge | 528b318 | 2017-01-23 08:51:59 -0800 | [diff] [blame^] | 1 | // Copyright 2016 Canonical Ltd. |
| 2 | // Licensed under the LGPLv3, see LICENCE file for details. |
| 3 | |
| 4 | package schema |
| 5 | |
| 6 | import ( |
| 7 | "reflect" |
| 8 | "time" |
| 9 | ) |
| 10 | |
| 11 | // TimeDuration returns a Checker that accepts a string value, and returns |
| 12 | // the parsed time.Duration value. Emtpy strings are considered empty time.Duration |
| 13 | func TimeDuration() Checker { |
| 14 | return timeDurationC{} |
| 15 | } |
| 16 | |
| 17 | type timeDurationC struct{} |
| 18 | |
| 19 | // Coerce implements Checker Coerce method. |
| 20 | func (c timeDurationC) Coerce(v interface{}, path []string) (interface{}, error) { |
| 21 | if v == nil { |
| 22 | return nil, error_{"string or time.Duration", v, path} |
| 23 | } |
| 24 | |
| 25 | var empty time.Duration |
| 26 | switch reflect.TypeOf(v).Kind() { |
| 27 | case reflect.TypeOf(empty).Kind(): |
| 28 | return v, nil |
| 29 | case reflect.String: |
| 30 | vstr := reflect.ValueOf(v).String() |
| 31 | if vstr == "" { |
| 32 | return empty, nil |
| 33 | } |
| 34 | v, err := time.ParseDuration(vstr) |
| 35 | if err != nil { |
| 36 | return nil, err |
| 37 | } |
| 38 | return v, nil |
| 39 | default: |
| 40 | return nil, error_{"string or time.Duration", v, path} |
| 41 | } |
| 42 | } |