du4010 2017-05-16 13:39
浏览 2226
已采纳

隐藏Golang Gorm中的字段

I am using Gorm in my Golang project. Exctly I have a Rest-API and I get a request make the process and return an object, so, for example I have a struct User like this:

type User struct {
    gorm.Model
    Password []byte
    Active bool
    Email string
    ActivationToken string
    RememberPasswordToken string
}

Now, when I create a User I am encoding it to JSON with:

json.NewEncoder(w).Encode(user)

But in the client side I am receiving some fields that I don't really want to send/receive, for example: Created_At, Deleted_At, Updated_At, Password. So, what is the best way to ignore or hide that fields in the response? I saw that I can use a library called Reflect, but it seems to be a lot of work for a simple thing and I want to know if there's another way. Thank you very much

  • 写回答

3条回答 默认 最新

  • dongxu7121 2017-05-16 16:41
    关注

    As Gavin said, I would suggest having two separate models and giving the model the ability to convert to the correct return type.

    models/user.go

    package models
    
    type User struct {
        gorm.Model
        Password []byte
        Active bool
        Email string
        ActivationToken string
        RememberPasswordToken string
    }
    
    func (u *User) UserToUser() app.User {
        return app.User{
            Email: u.Email
        }
    }
    

    app/user.go

    package app
    
    type User struct {
        Email string
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了