github.com/searKing/golang/go@v1.2.117/encoding/defaults/convert_test.go (about) 1 // Copyright 2022 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package defaults_test 6 7 import ( 8 "encoding/json" 9 "fmt" 10 "reflect" 11 "testing" 12 13 "github.com/searKing/golang/go/encoding/defaults" 14 ) 15 16 type inputType struct { 17 Name Name `default:"Alice"` 18 Age int `default:"10"` 19 IntArray []int `default:"[1,2,3]"` 20 StringArray []string `default:"[\"stdout\",\"./logs\"]"` 21 Map map[string]string `default:"{\"name\": \"Alice\", \"age\": \"18\"}"` 22 } 23 type Name string 24 25 func (name *Name) ConvertDefault(_ reflect.Value, _ reflect.StructTag) error { 26 if *name == "" { 27 *name = "Bob" 28 } 29 return nil 30 } 31 32 func (name *Name) Hello() error { 33 fmt.Printf("Hello\n") 34 return nil 35 } 36 37 func TestConvert(t *testing.T) { 38 i := &inputType{} 39 expect := &inputType{ 40 Name: "Bob", 41 Age: 10, 42 IntArray: []int{1, 2, 3}, 43 StringArray: []string{"stdout", "./logs"}, 44 Map: map[string]string{"name": "Alice", "age": "18"}, 45 } 46 err := defaults.Convert(i, json.Unmarshal) 47 if err != nil { 48 t.Error(err) 49 } 50 if !reflect.DeepEqual(i, expect) { 51 t.Errorf("expect\n[\n%v\n]\nactual[\n%v\n]", expect, i) 52 } 53 //reflect.ValueOf(&i.Name).MethodByName("Hello").Call(nil) 54 //reflect.ValueOf(&i.Name).MethodByName("ConvertDefault").Call(nil) 55 56 //fmt.Printf("converterType.Name %v %v\n", converterType.Name(), converterType.Method(0).Name) 57 58 //fmt.Printf("Name implement \n 1: %v 2: %v\n", 59 // reflect.ValueOf(&i.Name).MethodByName(converterType.Name()). 60 // Call([]reflect.Value{reflect.ValueOf(reflect.Value{}), reflect.ValueOf(reflect.StructField{})}),converterType.Name()) 61 62 }