doulu7258 2017-09-26 13:20
浏览 3139
已采纳

golang-忽略json属性而不被序列化的优雅方法

I've got a user struct, which has sensitive fields like password:

type User struct {
    UID string `json:"uid"  binding:"required"`
    Password string `json:"password" binding:"required"`
    EmailAddress string `json:"email" binding:"required"`
}

Now I want to be able to use this struct to register a user and update, delete but also to view. What I don't want is for the password to be serialized for viewing. I can, of course, make a custom marshaller but is that the only way? I tried using the json:"-" option but that causes it to be ignored while unmarshalling as well, which I don't want. Is there a better way?

EDIT: To put some of you guys at ease, I'm NOT going to be storing the password in plaintext, of course. It's the bcrypt hash of the password, but still. I don't want it to be returned when I search for users.

  • 写回答

4条回答 默认 最新

  • duandie0884 2017-09-26 14:18
    关注

    I'd say implementing json.Marshaler is the elegant solution if you want custom marshaling. It's quite simple in this case:

    func (u User) MarshalJSON() ([]byte, error) {
        type user User // prevent recursion
        x := user(u)
        x.Password = ""
        return json.Marshal(x)
    }
    

    Add "omitempty" in your User type if you don't want the password field at all when marshaling.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?