From 98db0dc8bc0f39213c3f93f7a08a5f96ce2e739c Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Tue, 7 Feb 2023 06:47:46 +0300 Subject: [PATCH] config/default: handle time.Duration Signed-off-by: Vasiliy Tolstov --- config/default.go | 26 ++++++++++++++++++++++---- config/default_test.go | 12 ++++++++---- 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/config/default.go b/config/default.go index 1acc0bdf..dd27ec68 100644 --- a/config/default.go +++ b/config/default.go @@ -5,9 +5,11 @@ import ( "reflect" "strconv" "strings" + "time" "github.com/imdario/mergo" rutil "go.unistack.org/micro/v3/util/reflect" + mtime "go.unistack.org/micro/v3/util/time" ) type defaultConfig struct { @@ -75,6 +77,7 @@ func fillValue(value reflect.Value, val string) error { if !rutil.IsEmpty(value) { return nil } + switch value.Kind() { case reflect.Map: t := value.Type() @@ -151,11 +154,26 @@ func fillValue(value reflect.Value, val string) error { } value.Set(reflect.ValueOf(int32(v))) case reflect.Int64: - v, err := strconv.ParseInt(val, 10, 64) - if err != nil { - return err + switch { + case value.Type().String() == "time.Duration" && value.Type().PkgPath() == "time": + v, err := time.ParseDuration(val) + if err != nil { + return err + } + value.Set(reflect.ValueOf(v)) + case value.Type().String() == "time.Duration" && value.Type().PkgPath() == "go.unistack.org/micro/v3/util/time": + v, err := mtime.ParseDuration(val) + if err != nil { + return err + } + value.SetInt(int64(v)) + default: + v, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return err + } + value.Set(reflect.ValueOf(v)) } - value.Set(reflect.ValueOf(v)) case reflect.Uint: v, err := strconv.ParseUint(val, 10, 0) if err != nil { diff --git a/config/default_test.go b/config/default_test.go index e7ebc0c4..180d687e 100644 --- a/config/default_test.go +++ b/config/default_test.go @@ -4,15 +4,19 @@ import ( "context" "fmt" "testing" + "time" "go.unistack.org/micro/v3/config" + mtime "go.unistack.org/micro/v3/util/time" ) type cfg struct { - StringValue string `default:"string_value"` - IgnoreValue string `json:"-"` - StructValue *cfgStructValue - IntValue int `default:"99"` + StringValue string `default:"string_value"` + IgnoreValue string `json:"-"` + StructValue *cfgStructValue + IntValue int `default:"99"` + DurationValue time.Duration `default:"10s"` + MDurationValue mtime.Duration `default:"10s"` } type cfgStructValue struct {