Hide fields in Golang Gorm

huangapple go评论69阅读模式
英文:

Hide fields in Golang Gorm

问题

我正在使用Gorm在我的Golang项目中。确切地说,我有一个Rest-API,我收到一个请求,进行处理并返回一个对象。例如,我有一个名为User的结构体:

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

现在,当我创建一个User时,我使用以下代码将其编码为JSON:

json.NewEncoder(w).Encode(user)

但是在客户端,我收到了一些我不想发送/接收的字段,例如:Created_At,Deleted_At,Updated_At,Password。那么,忽略或隐藏响应中的这些字段的最佳方法是什么?我看到可以使用一个叫做Reflect的库,但是这似乎对于一个简单的事情来说太麻烦了,我想知道是否还有其他方法。非常感谢。

英文:

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

答案1

得分: 14

如果你想要返回一个固定的对象,你可以使用json:"-"来更改标签,以决定要通过json发送的元素。
对于gorm.Model中的元素:

type Model struct {
    ID        uint `gorm:"primary_key"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `sql:"index"`
}

你可以用自己的结构体替换它们:

type OwnModel struct {
    ID        uint       `gorm:"primary_key"`
    CreatedAt time.Time  `json:"-"`
    UpdatedAt time.Time  `json:"-"`
    DeletedAt *time.Time `json:"-" sql:"index"`
}

因此,你的User结构体将会是这样的:

type User struct {
    OwnModel
    Password               []byte
    Active                 bool
    Email                  string
    ActivationToken        string
    RememberPasswordToken  string
}

其他的User字段是否添加json:"-"标签取决于你自己。

英文:

If you want to have a fixed object to return, you can change the tags with json:"-" to decide the elements to send with json.
For the elements in the gorm.Model:

type Model struct {
    ID        uint `gorm:"primary_key"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `sql:"index"`
}

You can substitute them for your own struct:

type OwnModel struct {
    ID        uint       `gorm:"primary_key"`
    CreatedAt time.Time  `json:"-"`
    UpdatedAt time.Time  `json:"-"`
    DeletedAt *time.Time `json:"-";sql:"index"`
}

So, your User struct would be like that:

type User struct {
    OwnModel
    Password []byte
    Active bool
    Email string
    ActivationToken string
    RememberPasswordToken string
}

The other User fields is your decision to add or not `json:"-"` tag.

答案2

得分: 12

对于我来说,帮助是将json:"-"添加到gorm.Model中。

例如:

type User struct {
    gorm.Model `json:"-"`
    Password []byte
    Active bool
    Email string
    ActivationToken string
    RememberPasswordToken string
}

这样做可以将gorm.Model字段在JSON序列化时忽略掉。

英文:

For me helped add json:"-" to gorm.Model

For example:

type User struct {
    gorm.Model `json:"-"`
    Password []byte
    Active bool
    Email string
    ActivationToken string
    RememberPasswordToken string
}

答案3

得分: 6

如Gavin所说,我建议使用两个单独的模型,并使模型具有转换为正确返回类型的能力。

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
}
英文:

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
}

答案4

得分: 0

我找到了一种方法来隐藏我的Sessions模型中与User模型的关联,方法是创建一个继承的结构体,并使用omitempty

// 用于隐藏结果中的User关联的技巧
type Session struct {
	models.Session
	User *models.User `json:"User,omitempty"`
}

func Token(c *fiber.Ctx) error {
	user := auth.User(c)
	var sessions []Session
	database.Db.Find(&sessions, "user_id = ?", user.ID)
	return render.Render(c, sessions)
}

希望这对你有帮助。我还添加了一个功能请求,我认为将这个功能内置到gorm中会很棒。

https://github.com/go-gorm/gorm/issues/5746

英文:

I found a way to hide the relation to my User model from my Sessions model by creating an inherited struct with an omitempty

// Trick to hide the User assocation from the results
type Session struct {
	models.Session
	User *models.User `json:"User,omitempty"`
}

func Token(c *fiber.Ctx) error {
	user := auth.User(c)
	var sessions []Session
	database.Db.Find(&sessions, "user_id = ?", user.ID)
	return render.Render(c, sessions)
}

I hope this helps - i also added a feature request - i think this would be great built-in to gorm

https://github.com/go-gorm/gorm/issues/5746

答案5

得分: -1

类型 OrmModel struct {
	gorm.Model `json:"-"`
	ID        uint  `gorm:"primarykey" json:"id,omitempty"`
}
类型 User struct {
    OrmModel
    Password []byte
    Active bool
    Email string
    ActivationToken string
    RememberPasswordToken string
}
英文:
type OrmModel struct {
	gorm.Model `json:"-"`
	ID        uint  `gorm:"primarykey" json:"id,omitempty"`
}
type User struct {
    OrmModel
    Password []byte
    Active bool
    Email string
    ActivationToken string
    RememberPasswordToken string
}

huangapple
  • 本文由 发表于 2017年5月16日 21:39:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/44003152.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定