1
votes

I am trying to get users from the DB with gorm and I get a 200 response but the user object got has empty values

{
    "id": "",
    "firstName": "",
    "lastName": "",
    "email": "",
    "createdAt": "0001-01-01T00:00:00Z",
    "updatedAt": "0001-01-01T00:00:00Z",
    "deletedAt": null
}

here is my model and my reg method

func (user *User) Get(db *gorm.DB, uid string) *errors.Error {
    fmt.Println("This is user ID %s", uid)

    var err error
    err = db.Debug().Model(User{}).Where("id = ?", uid).Take(&user).Error
    if err != nil {
        return errors.NewBadRequestError(fmt.Sprintf("error when trying to get user: %s", err.Error()))
    }
    if gorm.IsRecordNotFoundError(err) {
        return errors.NewBadRequestError(fmt.Sprintf("user not found: %s", err.Error()))
    }
    return nil
}

the model is

type User struct {
    ID string `gorm:"primary_key;" json:"id"`
    FirstName string     `gorm:"size:255;not null;column:firstName" json:"firstName"`
    LastName  string     `gorm:"size:255;not null;column:lastName" json:"lastName"`
    Email     string     `gorm:"size:100;not null;unique;column:email" json:"email"`
    CreatedAt time.Time  `gorm:"default:CURRENT_TIMESTAMP;column:createdAt" json:"createdAt"`
    UpdatedAt time.Time  `gorm:"default:CURRENT_TIMESTAMP;column:updatedAt" json:"updatedAt"`
    DeletedAt *time.Time `sql:"index;column:deletedAt" json:"deletedAt"`
}

my services logic

func GetUser(userId string) (*users.User, *errors.Error) {
    // result := &users.User{Base: {

    // }, }
    fmt.Println("This is user ID 2 %s", userId)
    result := &users.User{}
    if err := result.Get(database.DB, userId); err != nil {
        return nil, err
    }
    return &users.User{}, nil
}

my controller

func GetUser(c *gin.Context) {
    userId := c.Param("user_id")
    fmt.Println(userId)

    user, getErr := services.GetUser(userId)
    if getErr != nil {
        // TODO: handle user createing error
        c.JSON(getErr.Status, getErr)
        return
    }
    c.JSON(http.StatusOK, user)
}
1
You're passing a pointer to a pointer to Take (user is already of type *User).Peter
What do you mean @PeterKing

1 Answers

2
votes

In your service logic, you are returning a pointer and not a value.

func GetUser(userId string) (*users.User, *errors.Error) {

  fmt.Println("This is user ID 2 %s", userId)
  result := &users.User{}
  if err := result.Get(database.DB, userId); err != nil {
    return nil, err
  }
  return &users.User{}, nil
}

It should be:

func GetUser(userId string) (*users.User, *errors.Error) {
    fmt.Println("This is user ID 2 %s", userId)
    result := &users.User{ID: userId}
    if err := result.Get(database.DB, userId); err != nil {
        return nil, err
    }
    return result, nil
}