golang-忽略json属性而不被序列化的优雅方法 [英] golang - elegant way to omit a json property from being serialized
问题描述
我有一个用户结构,其中包含诸如密码之类的敏感字段:
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"`
}
现在,我希望能够使用此结构来注册用户并进行更新,删除和查看.我不希望将密码序列化以供查看.我当然可以做一个自定义编组员,但这是唯一的方法吗?我尝试使用 json:-"
选项,但是这也会在取消编组时将其忽略,这是我不希望的.有更好的方法吗?
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?
为了让大家放松,我当然不会以明文形式存储密码.它是密码的bcrypt哈希,但仍然如此.我不希望在搜索用户时将其返回.
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.
推荐答案
我想说实现json.如果您要自定义封送处理,Marshaler是一个优雅的解决方案.在这种情况下很简单:
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)
}
如果在编组时根本不需要密码字段,请在用户类型"中添加"omitempty".
Add "omitempty" in your User type if you don't want the password field at all when marshaling.
这篇关于golang-忽略json属性而不被序列化的优雅方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!