Skip to content

Commit 0fccfd9

Browse files
authored
Merge pull request #3 from bc-vincent-zhao/add-duration-support
support time.Duration default value
2 parents 34bab33 + 1c4c89e commit 0fccfd9

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ type ExampleBasic struct {
2727
Foo bool `default:"true"` //<-- StructTag with a default key
2828
Bar string `default:"33"`
2929
Qux int8
30+
Dur time.Duration `default:"1m"`
3031
}
3132

3233
func NewExampleBasic() *ExampleBasic {
@@ -42,7 +43,7 @@ test := NewExampleBasic()
4243
fmt.Println(test.Foo) //Prints: true
4344
fmt.Println(test.Bar) //Prints: 33
4445
fmt.Println(test.Qux) //Prints:
45-
46+
fmt.Println(test.Dur) //Prints: 1m0s
4647
```
4748

4849
License

defaults.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package defaults
33
import (
44
"reflect"
55
"strconv"
6+
"time"
67
)
78

89
// Applies the default values to the struct object, the struct type must have
@@ -84,5 +85,11 @@ func newDefaultFiller() *Filler {
8485
getDefaultFiller().SetDefaultValues(fields)
8586
}
8687

87-
return &Filler{FuncByKind: funcs, Tag: "default"}
88+
types := make(map[TypeHash]FillerFunc, 1)
89+
types["time.Duration"] = func(field *FieldData) {
90+
d, _ := time.ParseDuration(field.TagValue)
91+
field.Value.Set(reflect.ValueOf(d))
92+
}
93+
94+
return &Filler{FuncByKind: funcs, FuncByType: types, Tag: "default"}
8895
}

defaults_test.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package defaults
22

33
import (
44
"testing"
5+
"time"
56

67
. "gopkg.in/check.v1"
78
)
@@ -33,6 +34,7 @@ type ExampleBasic struct {
3334
Bool bool `default:"true"`
3435
Integer int `default:"33"`
3536
}
37+
Duration time.Duration `default:"1s"`
3638
}
3739

3840
func (s *DefaultsSuite) TestSetDefaultsBasic(c *C) {
@@ -70,6 +72,7 @@ func (s *DefaultsSuite) assertTypes(c *C, foo *ExampleBasic) {
7072
c.Assert(foo.Float32, Equals, float32(3.2))
7173
c.Assert(foo.Float64, Equals, 6.4)
7274
c.Assert(foo.Struct.Bool, Equals, true)
75+
c.Assert(foo.Duration, Equals, time.Second)
7376
}
7477

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

0 commit comments

Comments
 (0)