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

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 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 matlab求解平差
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办