From 88a966ef17e56e285a372bee6786dda845bc04bf Mon Sep 17 00:00:00 2001 From: john Date: Fri, 2 Nov 2018 13:13:01 +0800 Subject: [PATCH] =?UTF-8?q?gconv=E5=A2=9E=E5=8A=A0=E5=AF=B9=E5=B8=A6'=20'?= =?UTF-8?q?=E5=8F=82=E6=95=B0=E9=94=AE=E5=90=8D=E5=88=B0struct=E5=B1=9E?= =?UTF-8?q?=E6=80=A7=E7=9A=84=E8=BD=AC=E6=8D=A2=EF=BC=8C=E5=A6=82:nick=20n?= =?UTF-8?q?ame=20=3D>=20struct.NickName=EF=BC=8C=E5=B9=B6=E5=AE=8C?= =?UTF-8?q?=E5=96=84=E7=A4=BA=E4=BE=8B=E7=A8=8B=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- g/util/gconv/gconv_struct.go | 13 +++++++++---- geg/util/gconv/gconv_struct1.go | 27 ++++++++++++++++----------- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/g/util/gconv/gconv_struct.go b/g/util/gconv/gconv_struct.go index 8f3441dd2..869be54ca 100644 --- a/g/util/gconv/gconv_struct.go +++ b/g/util/gconv/gconv_struct.go @@ -91,21 +91,26 @@ func Struct(params interface{}, objPointer interface{}, attrMapping...map[string } for mapk, mapv := range paramsMap { name := "" - for _, v := range []string{ + for _, checkName := range []string { gstr.UcFirst(mapk), gstr.ReplaceByMap(mapk, map[string]string{ "_" : "", "-" : "", + " " : "", })} { - if _, ok := dmap[v]; ok { + if _, ok := dmap[checkName]; ok { continue } - if _, ok := tagmap[v]; ok { + if _, ok := tagmap[checkName]; ok { continue } // 循环查找属性名称进行匹配 attrset.Iterator(func(value string) bool { - if strings.EqualFold(value, v) { + if strings.EqualFold(checkName, value) { + name = value + return false + } + if strings.EqualFold(checkName, gstr.Replace(value, "_", "")) { name = value return false } diff --git a/geg/util/gconv/gconv_struct1.go b/geg/util/gconv/gconv_struct1.go index 5481c1599..cee49b7c1 100644 --- a/geg/util/gconv/gconv_struct1.go +++ b/geg/util/gconv/gconv_struct1.go @@ -1,16 +1,17 @@ package main import ( - "fmt" "gitee.com/johng/gf/g" "gitee.com/johng/gf/g/util/gconv" ) type User struct { - Uid int - Name string - Pass1 string `gconv:"password1"` - Pass2 string `gconv:"password2"` + Uid int + Name string + Site_Url string + NickName string + Pass1 string `gconv:"password1"` + Pass2 string `gconv:"password2"` } func main() { @@ -19,13 +20,15 @@ func main() { // 使用默认映射规则绑定属性值到对象 user = new(User) params1 := g.Map{ - "uid" : 1, - "Name" : "john", - "PASS1" : "123", - "PaSs2" : "456", + "uid" : 1, + "Name" : "john", + "siteurl" : "https://gfer.me", + "nick_name" : "johng", + "PASS1" : "123", + "PASS2" : "456", } if err := gconv.Struct(params1, user); err == nil { - fmt.Println(user) + g.Dump(user) } // 使用struct tag映射绑定属性值到对象 @@ -33,10 +36,12 @@ func main() { params2 := g.Map { "uid" : 2, "name" : "smith", + "site-url" : "https://gfer.me", + "nick name" : "johng", "password1" : "111", "password2" : "222", } if err := gconv.Struct(params2, user); err == nil { - fmt.Println(user) + g.Dump(user) } } \ No newline at end of file