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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址