Skip to content
Open
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
18 changes: 18 additions & 0 deletions defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"reflect"
"strconv"
"strings"
"time"
)

Expand Down Expand Up @@ -65,6 +66,9 @@ func setField(field reflect.Value, defaultVal string) error {
if unmarshalByInterface(field, defaultVal) {
return nil
}
if parseByMethod(field, defaultVal) {
return nil
}

switch field.Kind() {
case reflect.Bool:
Expand Down Expand Up @@ -217,6 +221,20 @@ func unmarshalByInterface(field reflect.Value, defaultVal string) bool {
return false
}

func parseByMethod(field reflect.Value, defaultVal string) bool {
if field.Type() == reflect.TypeOf(time.Duration(0)) {
if defaultVal != "" {
defaultVal = strings.TrimSpace(defaultVal)
duration, err := time.ParseDuration(defaultVal)
if err == nil {
field.Set(reflect.ValueOf(duration))
return true
}
}
}
return false
}

func isInitialValue(field reflect.Value) bool {
return reflect.DeepEqual(reflect.Zero(field.Type()).Interface(), field.Interface())
}
Expand Down
3 changes: 3 additions & 0 deletions defaults_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,9 @@ func TestInit(t *testing.T) {
if sample.String != "hello" {
t.Errorf("it should initialize string")
}
if sample.Duration != 10000000000 {
t.Errorf("it should initialize time.Duration")
}

if sample.IntOct != 0o1 {
t.Errorf("it should initialize int with octal literal")
Expand Down