golang使用gorm返回指定字段

1,252 阅读1分钟

问题:使用gin框架接口返回筛选后的字段(并且所有字段小写显示)

思路: 通过结构体指定相关的字段,并对这些字段进行一些限制,最后使用gorm查询数据,对声明接收数据的变量用该结构体进行限定,具体代码如下:

type limitField struct {// 接口返回使用小写 
		ID         uint       `json:"id"`
		UserId     string     `json:"user_id"`
		Name       string     `json:"name"`
		Phone      string     `json:"phone"`
		Email      string     `json:"email"`
		Gender     uint       `json:"gender"`
		AvatarUrl  string     `json:"avatar_url"`
		Country    string     `json:"country"`
		Province   string     `json:"province"`
		City       string     `json:"city"`
		NickName   string     `json:"nick_name"`
		UserStatus string     `json:"user_status"`
		IsAdmin    bool       `json:"is_admin"`
		LineTime   *time.Time `json:"line_time"`
	}

	var userList []limitField  // 就是这个限定
	FindError := models.DB.Model(&models.User{}).Offset(pageNumber).Limit(pageSize).Where("is_admin = ?", 0).Scan(&userList).Error
	if FindError != nil {
		fmt.Println(FindError)
		c.JSON(http.StatusOK, gin.H{
			"code":    "-1",
			"message": "查询数据异常111",
			"data":    gin.H{},
		})
		return
	}

具体返回的数据如下:

{
	"code": "200",
	"data": {
		"currentPage": 1,
		"data": [
			{
				"id": 2,
				"user_id": "weexss@126.com",
				"name": "",
				"phone": "",
				"email": "weexss@126.com",
				"gender": 0,
				"avatar_url": "",
				"country": "",
				"province": "",
				"city": "",
				"nick_name": "",
				"user_status": "",
				"is_admin": false,
				"line_time": null
			},
		],
		"pageSize": 10,
		"total": 1
	},
	"message": "success"
}

以上就是gorm使用接口(gin)返回指定的小写字段