Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably worth documenting this expected format in the README, for example here.

if err != nil {
return err
}
value.Set(reflect.ValueOf(d))
return nil
}

switch t.Kind() {
case reflect.Bool:
b, err := strconv.ParseBool(data)
Expand Down
10 changes: 7 additions & 3 deletions config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
}

Expand Down