config: move reflect stuff to util/reflect

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
2021-01-19 01:40:34 +03:00
parent 4783c6d9a3
commit 770e8425bd
3 changed files with 11 additions and 4 deletions

View File

@@ -5,6 +5,8 @@ import (
"reflect"
"strconv"
"strings"
rutil "github.com/unistack-org/micro/v3/util/reflect"
)
type defaultConfig struct {
@@ -45,7 +47,7 @@ func (c *defaultConfig) Load(ctx context.Context) error {
}
func (c *defaultConfig) fillValue(ctx context.Context, value reflect.Value, val string) error {
if !IsEmpty(value) {
if !rutil.IsEmpty(value) {
return nil
}
switch value.Kind() {

View File

@@ -1,46 +0,0 @@
package config
import (
"reflect"
)
func IsEmpty(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Ptr:
if v.IsNil() {
return true
}
return IsEmpty(v.Elem())
case reflect.Func:
return v.IsNil()
case reflect.Invalid:
return true
}
return false
}
func Zero(src interface{}) (interface{}, error) {
sv := reflect.ValueOf(src)
if sv.Kind() == reflect.Ptr {
sv = sv.Elem()
}
if sv.Kind() == reflect.Invalid {
return nil, ErrInvalidStruct
}
dst := reflect.New(sv.Type())
return dst.Interface(), nil
}

View File

@@ -3,7 +3,7 @@ package config_test
import (
"testing"
"github.com/unistack-org/micro/v3/config"
rutil "github.com/unistack-org/micro/v3/util/reflect"
)
type Config struct {
@@ -18,7 +18,7 @@ type SubConfig struct {
func TestReflect(t *testing.T) {
cfg1 := &Config{Value: "cfg1", Config: &Config{Value: "cfg1_1"}, SubConfig: &SubConfig{Value: "cfg1"}}
cfg2, err := config.Zero(cfg1)
cfg2, err := rutil.Zero(cfg1)
if err != nil {
t.Fatal(err)
}