Search code examples
jsongogo-gorm

Hide fields in 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


Solution

  • 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
    }