diff --git a/README.md b/README.md index 9a09a00..efd8609 100644 --- a/README.md +++ b/README.md @@ -38,9 +38,12 @@ type Config struct { Host string `config:"host"` Port uint32 `config:"port"` Timeout time.Duration `config:"timeout"` + SomeVal *time.Time `config:"someval"` } ``` +Time is expected to be in `RFC3339` format. + By default, all fields are optional. With the required option, if a key is not found then Confita will return an error. ```go diff --git a/config.go b/config.go index d472e1c..648bcdd 100644 --- a/config.go +++ b/config.go @@ -263,6 +263,7 @@ func (f *FieldConfig) Set(data string) error { } var durationType = reflect.TypeOf(time.Duration(0)) +var timeType = reflect.TypeOf(time.Time{}) func convert(data string, value reflect.Value) error { t := value.Type() @@ -274,6 +275,16 @@ func convert(data string, value reflect.Value) error { value.SetInt(int64(d)) return nil } + + if t == timeType { + d, err := time.Parse(time.RFC3339, data) + if err != nil { + return err + } + value.Set(reflect.ValueOf(d)) + return nil + } + switch t.Kind() { case reflect.Bool: b, err := strconv.ParseBool(data) diff --git a/config_test.go b/config_test.go index 623ca37..ac176d0 100644 --- a/config_test.go +++ b/config_test.go @@ -82,6 +82,7 @@ func TestLoad(t *testing.T) { Ptr *string `config:"ptr"` String string `config:"string"` Duration time.Duration `config:"duration"` + Time *time.Time `config:"time"` Struct nested StructPtrNil *nested StructPtrNotNil *nested @@ -117,10 +118,12 @@ func TestLoad(t *testing.T) { "float64": strconv.FormatFloat(math.MaxFloat64, 'f', 6, 64), } + date := time.Now().UTC().Truncate(time.Second) otherStore := store{ "ptr": "ptr", "string": "string", "duration": "10s", + "time": date.Format(time.RFC3339), } loader := confita.NewLoader( @@ -150,6 +153,7 @@ func TestLoad(t *testing.T) { Ptr: &ptr, String: "string", Duration: 10 * time.Second, + Time: &date, Struct: nested{ Int: math.MaxInt64, String: "string", @@ -190,13 +194,13 @@ func TestLoadIgnored(t *testing.T) { func TestLoadFirstBackendWins(t *testing.T) { s := struct { - Age int `config:"age"` + Age int `config:"age"` }{} st1 := store{ - "age": "10", + "age": "10", } - st2 := store { + st2 := store{ "age": "77", }