1

I used go-swagger and gorm for MySQL queries and one of my handlers is (retreiving one record)

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()
})

or retreive all data from table users

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 struct is

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)`
}

and same as models.Users

How properly return data there? I tried with WriteResponse and WithPayload but unsuccessful

robbieperry22
  • 1,753
  • 1
  • 18
  • 49
Sasa Jovanovic
  • 324
  • 2
  • 14

1 Answers1

0

There is an answer:

First change

user := User{}

to

user := new(models.Users)

and add at the end

        ret := make([]*models.Users, 0)

        ret = append(ret, user)
        return users.NewUserGetByIDOK().WithPayload(ret)

WithPayload functions form file *_responses.go is defined as

// 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
}
Sasa Jovanovic
  • 324
  • 2
  • 14