Skip to content

Commit fb68a23

Browse files
russmatneymcuadros
authored andcommitted
parses default time.Duration via time.ParseDuration (cherry-pick)
1 parent e1c978b commit fb68a23

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ A basic example:
2121
import (
2222
"fmt"
2323
"github.com/mcuadros/go-defaults"
24+
"time"
2425
)
2526

2627
type ExampleBasic struct {

defaults.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
// Foo bool `default:"true"`
1515
// Bar string `default:"33"`
1616
// Qux int8
17+
// Dur time.Duration `default:"2m3s"`
1718
// }
1819
//
1920
// foo := &ExampleBasic{}
@@ -47,7 +48,15 @@ func newDefaultFiller() *Filler {
4748
funcs[reflect.Int8] = funcs[reflect.Int]
4849
funcs[reflect.Int16] = funcs[reflect.Int]
4950
funcs[reflect.Int32] = funcs[reflect.Int]
50-
funcs[reflect.Int64] = funcs[reflect.Int]
51+
funcs[reflect.Int64] = func(field *FieldData) {
52+
if field.Field.Type == reflect.TypeOf(time.Second) {
53+
value, _ := time.ParseDuration(field.TagValue)
54+
field.Value.Set(reflect.ValueOf(value))
55+
} else {
56+
value, _ := strconv.ParseInt(field.TagValue, 10, 64)
57+
field.Value.SetInt(value)
58+
}
59+
}
5160

5261
funcs[reflect.Float32] = func(field *FieldData) {
5362
value, _ := strconv.ParseFloat(field.TagValue, 64)

defaults_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ type ExampleBasic struct {
4545
}
4646
Duration time.Duration `default:"1s"`
4747
Children []Child
48+
Second time.Duration `default:"1s"`
4849
}
4950

5051
func (s *DefaultsSuite) TestSetDefaultsBasic(c *C) {
@@ -84,6 +85,7 @@ func (s *DefaultsSuite) assertTypes(c *C, foo *ExampleBasic) {
8485
c.Assert(foo.Struct.Bool, Equals, true)
8586
c.Assert(foo.Duration, Equals, time.Second)
8687
c.Assert(foo.Children, IsNil)
88+
c.Assert(foo.Second, Equals, time.Second)
8789
}
8890

8991
func (s *DefaultsSuite) TestSetDefaultsWithValues(c *C) {

0 commit comments

Comments
 (0)