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 | // Time returns a Checker that accepts a string value, and returns |
| 12 | // the parsed time.Time value. Emtpy strings are considered empty times. |
| 13 | func Time() Checker { |
| 14 | return timeC{} |
| 15 | } |
| 16 | |
| 17 | type timeC struct{} |
| 18 | |
| 19 | // Coerce implements Checker Coerce method. |
| 20 | func (c timeC) Coerce(v interface{}, path []string) (interface{}, error) { |
| 21 | if v == nil { |
| 22 | return nil, error_{"string or time.Time", v, path} |
| 23 | } |
| 24 | var empty time.Time |
| 25 | switch reflect.TypeOf(v).Kind() { |
| 26 | case reflect.TypeOf(empty).Kind(): |
| 27 | return v, nil |
| 28 | case reflect.String: |
| 29 | vstr := reflect.ValueOf(v).String() |
| 30 | if vstr == "" { |
| 31 | return empty, nil |
| 32 | } |
| 33 | v, err := time.Parse(time.RFC3339Nano, vstr) |
| 34 | if err != nil { |
| 35 | return nil, err |
| 36 | } |
| 37 | return v, nil |
| 38 | default: |
| 39 | return nil, error_{"string or time.Time", v, path} |
| 40 | } |
| 41 | } |