如何用搜索到的数据写回信

问题描述 投票:0回答:1

我使用go-swagger和gorm进行MySQL查询,我的一个处理程序是(获取一条记录)

api.UsersUserGetByIDHandler = users.UserGetByIDHandlerFunc(func(params users.UserGetByIDParams) middleware.Responder {
    db := dbConn()
    user := User{}
    res := db.Table("users").Where("id = ?", params.UserID).Select("id, email, password, name").Scan(&user)
    if res.RecordNotFound() {
        message := "User not exists"
        return users.NewUserGetByIDDefault(500).WithPayload(&models.Error{Message: &message})
    }
    log.Info(user) // {21 bxffcgb@emagggil.com 123456 Second}


    return users.NewUserGetByIDOK()  //How return right response there??? 
    //.WriteResponse()
})

或检索表用户的所有数据

api.UsersUserListHandler = users.UserListHandlerFunc(func(params users.UserListParams) middleware.Responder {
        db := dbConn()
var user []User
        var count int
        db.Table("users").Select("id, email, password, name").Scan(&user).Count(&count)

        log.Info(db.RecordNotFound())
        if count == 0 {
            message := "User not exists"
            return users.NewUserGetByIDDefault(500).WithPayload(&models.Error{Message: &message})
        }

        return users.NewUserGetByIDOK()
    })

User Gorm结构是

type User struct { // user
    ID       int64  `gorm:"AUTO_INCREMENT"`
    Email    string `gorm:"type:varchar(200);unique_index"`
    Password string `gorm:"size:200"`
    Name     string `gorm:"type:varchar(200)`
}

与模型相同。用户

如何正确返回数据?我尝试了WriteResponse和WithPayload,但未成功

go struct gorm go-gorm go-swagger
1个回答
0
投票
// WithPayload adds the payload to the user get by Id o k response func (o *UserGetByIDOK) WithPayload(payload []*models.Users) *UserGetByIDOK { o.Payload = payload return o }
热门问题
推荐问题
最新问题