dqyy38265 2015-07-19 19:17
浏览 6
已采纳

验证结构字段(如果存在)

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?

  • 写回答

1条回答 默认 最新

  • duai3681 2015-07-19 19:30
    关注

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

    <kbd>playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分