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 全志H618ROM新增分区
  • ¥20 jupyter保存图像功能的实现
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况