drll42469 2018-06-25 17:25
浏览 45
已采纳

如何从对象中删除属性

I have a User struct:

type User struct {
    gorm.Model
    Email         string
    Password      string
    AccountType   int
    CompanyId     int
    FirstName     string
    LastName      string
    PhoneNumber   string
    RecoveryEmail string
    Contractor    bool `gorm:"sql:'not null' default:'false'"`
}

I'm using this struct to get a row from the database using gorm:

// Get a specific user from the database.
func getUser(id uint) (*User, error) {

    var user User

    if err := database.Connection.Select("id, created_at, email, account_type, company_id, first_name, last_name").Where("id = ? ", id).First(&user).Error; err != nil {
        return nil, err
    }

    fmt.Println(&user)
    return &user, nil
}

My Gin hanlder:

// @Summary Attempts to get a existing user by id
// @tags users
// @Router /api/users/getUserById [get]
func HandleGetUserById(c *gin.Context) {
    // Were using delete params as it shares the same interface.
    var json deleteParams

    if err := c.Bind(&json); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"message": "No user ID found, please try again."})
        return
    }

    outcome, err := getUser(json.Id)

    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong while trying to process that, please try again.", "error": err.Error()})
        log.Println(err)
        return
    }

    c.JSON(http.StatusOK, gin.H{
        "message": "Successfully found user",
        "user":    outcome,
    })

}

It returns back everything fine, but when I return &user the fields not selected are returned back with default values:

{
    "message": "Successfully found user",
    "user": {
        "ID": 53,
        "CreatedAt": "2018-06-24T00:05:49.761736+01:00",
        "UpdatedAt": "0001-01-01T00:00:00Z",
        "DeletedAt": null,
        "Email": "jack@jackner.com",
        "Password": "",
        "AccountType": 0,
        "CompanyId": 2,
        "FirstName": "",
        "LastName": "",
        "PhoneNumber": "",
        "RecoveryEmail": "",
        "Contractor": false
    }
}

Is there a way in go to remove empty or null properties from an object? Or will I have to send back an object instead with the values mapped to said new object? If there's a simple way of doing the former with a helper function I'd like to know how.

  • 写回答

1条回答 默认 最新

  • dtlh12053 2018-06-25 17:50
    关注

    You can specify the omitempty tag in your object's fields definitions.

    Example:

    Email string `json:",omitempty"`
    

    If you define the fields that way, empty values will not be present in the JSON output:

    https://golang.org/pkg/encoding/json/#Marshal

    The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答