blob: 71e75fe37aa599f05d0ceec4716ab3ba1663c5df [file] [log] [blame]
David K. Bainbridge528b3182017-01-23 08:51:59 -08001// Copyright 2016 Canonical Ltd.
2// Licensed under the LGPLv3, see LICENCE file for details.
3
4package schema
5
6import (
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
13func TimeDuration() Checker {
14 return timeDurationC{}
15}
16
17type timeDurationC struct{}
18
19// Coerce implements Checker Coerce method.
20func (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}