config/default: handle time.Duration #182

Merged
vtolstov merged 3 commits from timeDuration into v3 2023-02-07 06:50:42 +03:00
2 changed files with 30 additions and 8 deletions
Showing only changes of commit 98db0dc8bc - Show all commits

View File

@ -5,9 +5,11 @@ import (
"reflect" "reflect"
"strconv" "strconv"
"strings" "strings"
"time"
"github.com/imdario/mergo" "github.com/imdario/mergo"
rutil "go.unistack.org/micro/v3/util/reflect" rutil "go.unistack.org/micro/v3/util/reflect"
mtime "go.unistack.org/micro/v3/util/time"
) )
type defaultConfig struct { type defaultConfig struct {
@ -75,6 +77,7 @@ func fillValue(value reflect.Value, val string) error {
if !rutil.IsEmpty(value) { if !rutil.IsEmpty(value) {
return nil return nil
} }
switch value.Kind() { switch value.Kind() {
case reflect.Map: case reflect.Map:
t := value.Type() t := value.Type()
@ -151,11 +154,26 @@ func fillValue(value reflect.Value, val string) error {
} }
value.Set(reflect.ValueOf(int32(v))) value.Set(reflect.ValueOf(int32(v)))
case reflect.Int64: case reflect.Int64:
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) v, err := strconv.ParseInt(val, 10, 64)
if err != nil { if err != nil {
return err return err
} }
value.Set(reflect.ValueOf(v)) value.Set(reflect.ValueOf(v))
}
case reflect.Uint: case reflect.Uint:
v, err := strconv.ParseUint(val, 10, 0) v, err := strconv.ParseUint(val, 10, 0)
if err != nil { if err != nil {

View File

@ -4,8 +4,10 @@ import (
"context" "context"
"fmt" "fmt"
"testing" "testing"
"time"
"go.unistack.org/micro/v3/config" "go.unistack.org/micro/v3/config"
mtime "go.unistack.org/micro/v3/util/time"
) )
type cfg struct { type cfg struct {
@ -13,6 +15,8 @@ type cfg struct {
IgnoreValue string `json:"-"` IgnoreValue string `json:"-"`
StructValue *cfgStructValue StructValue *cfgStructValue
IntValue int `default:"99"` IntValue int `default:"99"`
DurationValue time.Duration `default:"10s"`
MDurationValue mtime.Duration `default:"10s"`
} }
type cfgStructValue struct { type cfgStructValue struct {