验证struct字段是否存在 [英] Validate struct field if it exists

查看:123
本文介绍了验证struct字段是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

 

code> err:= json.NewDecoder(req.Body).Decode(user)
//处理错误,如果有一个

和'User'结构:

 类型User struct {
名字字符串`json:name,omitempty`
用户名字符串`json:username,omitempty`
电子邮件字符串`json:email,omitempty`
城镇字符串`json :town,omitempty`
// more fields here
}

尽管我不需要实际验证方面的帮助,但我想知道如何验证用户名,只有当它包含在JSON对象中时才是如此。目前,如果没有包含用户名,那么 User.Username 仍然存在,但是为空,即



如何检查''username''是否包含在POSTed对象中?

$ b $你可以使用一个指向字符串的指针:

  >类型User struct {
名称字符串`json:name,omitempty`
用户名*字符串`json:username,omitempty`
电子邮件字符串`json:email,omitempty `
Town string`json:town,omitempty`
//更多字段
}

func main(){
var u, u2 User
json.Unmarshal([] byte(`{username:hi}`),& u)
fmt.Println(username set:,u.Username!= nil,* u.Username)
json.Unmarshal([] byte(`{}`),& u2)
fmt.Println(username set:,u2.Username!= nil)
fmt.Println(Hello,playground)
}

playground


I'm POSTing a JSON user object to my Golang application where I decode the 'req.body' into a 'User' struct.

err := json.NewDecoder(req.Body).Decode(user)
//handle err if there is one

and the 'User' struct:

type User struct {
    Name      string  `json:"name,omitempty"`
    Username  string  `json:"username,omitempty"`
    Email     string  `json:"email,omitempty"`
    Town      string  `json:"town,omitempty"`
    //more fields here
}

While I don't need help with the actual validation, I would like know how to validate usernames only if it is included as part of the JSON object. At the moment, if a username isn't included then User.Username will still exist but be empty i.e. ""

How can I check to see if '"username"' was included as part of the POSTed object?

解决方案

You can use a pointer to a string:

type User struct {
    Name     string  `json:"name,omitempty"`
    Username *string `json:"username,omitempty"`
    Email    string  `json:"email,omitempty"`
    Town     string  `json:"town,omitempty"`
    //more fields here
}

func main() {
    var u, u2 User
    json.Unmarshal([]byte(`{"username":"hi"}`), &u)
    fmt.Println("username set:", u.Username != nil, *u.Username)
    json.Unmarshal([]byte(`{}`), &u2)
    fmt.Println("username set:", u2.Username != nil)
    fmt.Println("Hello, playground")
}

playground

这篇关于验证struct字段是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆