【问题标题】:Hide fields in Golang Gorm在 Golang Gorm 中隐藏字段
【发布时间】:2019-03-13 20:08:49
【问题描述】:

我在我的 Golang 项目中使用 Gorm。正是我有一个 Rest-API 并且我收到了一个请求,使该进程并返回一个对象,所以,例如,我有一个这样的 struct User:

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

现在,当我创建用户时,我将其编码为 JSON:

json.NewEncoder(w).Encode(user)

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

【问题讨论】:

  • 对于要返回和存储在数据库中的内容有单独的模型,不要导出该字段,或者您可以使用 json 属性忽略该字段,即Password []byte `json:'-'`
  • @Gavin,是否可以在外部结构上更改这些属性?
  • @william.taylor.09 什么时候提到的结构是外部的?
  • gorm.Model 在 User 结构中包含匿名字段。我假设 OP 希望限制对这些字段的可见性。
  • @william.taylor.09 啊,是的,你是对的。我可能会为响应制作一个单独的模型。这听起来像是最简单的解决方案,并且还将数据库特定信息与最终用户看到的信息分开。

标签: json go go-gorm


【解决方案1】:

如果你想返回一个固定的对象,你可以用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
}

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

【讨论】:

    【解决方案2】:

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

    例如:

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

    【讨论】:

      【解决方案3】:

      正如 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
      }
      

      【讨论】:

      • 如果我们使用预加载/连接,我们是否必须循环每个对象才能将其转换为其他结构?
      猜你喜欢
      • 2020-11-26
      • 1970-01-01
      • 2013-04-06
      • 2011-02-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      • 2011-01-02
      • 2012-05-17
      相关资源
      最近更新 更多