我在我的 Golang 项目中使用 Gorm。确切地说,我有一个 Rest-API 并且我收到一个请求来执行该过程并返回一个对象,因此,例如我有一个像这样的 struct User:
type User struct {
gorm.Model
Password []byte
Active bool
Email string
ActivationToken string
RememberPasswordToken string
}
Run Code Online (Sandbox Code Playgroud)
现在,当我创建一个用户时,我将其编码为 JSON:
json.NewEncoder(w).Encode(user)
Run Code Online (Sandbox Code Playgroud)
但在客户端,我收到了一些我不想发送/接收的字段,例如:Created_At、Deleted_At、Updated_At、密码。那么,在响应中忽略或隐藏该字段的最佳方法是什么?我看到我可以使用一个名为 Reflect 的库,但是对于一件简单的事情来说似乎需要做很多工作,我想知道是否有另一种方法。非常感谢
小智 12
如果您想返回一个固定的对象,您可以更改标签json:"-"以决定使用 json 发送的元素。对于 gorm.Model 中的元素:
type Model struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index"`
}
Run Code Online (Sandbox Code Playgroud)
您可以将它们替换为您自己的结构:
type OwnModel struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt *time.Time `json:"-";sql:"index"`
}
Run Code Online (Sandbox Code Playgroud)
因此,您的 User 结构将是这样的:
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.
Run Code Online (Sandbox Code Playgroud)
小智 7
对我来说帮助添加json:"-"到 gorm.Model
例如:
type User struct {
gorm.Model `json:"-"`
Password []byte
Active bool
Email string
ActivationToken string
RememberPasswordToken string
}
Run Code Online (Sandbox Code Playgroud)
正如 Gavin 所说,我建议有两个单独的模型,并让模型能够转换为正确的返回类型。
模型/用户.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
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序/用户.go
package app
type User struct {
Email string
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5294 次 |
| 最近记录: |