gconv增加对带' '参数键名到struct属性的转换,如:nick name => struct.NickName,并完善示例程序

This commit is contained in:
john
2018-11-02 13:13:01 +08:00
parent e7c60f11e1
commit 88a966ef17
2 changed files with 25 additions and 15 deletions

View File

@ -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
}

View File

@ -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)
}
}