0

I am trying to fetch full table details using go language , but not getting

func GetallUserHandler(c *gin.Context) {

    // fetch data
    userdata, selectErr := views.GetallUser()
    if selectErr != nil {
        c.JSON(http.StatusInternalServerError, fmt.Sprintf("Something wrong on our server"))
        database.Dberror(selectErr)
    } else {
        c.JSON(http.StatusOK, userdata)
    }
}



func GetallUser() error {
    db := database.DbConnection()
    defer db.Close()
    query := "Select * from user;"
    rows, queryErr := db.Query(query)
    database.Dberror(queryErr)

    defer rows.Close()
    for rows.Next() {
        user := models.User{}
        queryErr = rows.Scan(&user.Id, &user.Username, &user.Password, &user.Firstname)
    }
    queryErr = rows.Err()
    database.Dberror(queryErr)

}

in GetallUser() function , I am stuck here .

How can I return the all table details?

please help

Mia Mia
  • 143
  • 12
  • The GetallUser() currently is only returning an error but you are trying to read userdata as well as an error? I am assuming based on your code that you need to return a slice of model.User along with an error. You should create a slice users := model.User{} and append each user you are reading inside the for loop to this slice. You also need a return statement returning this slice of users and an error if any. – Haril Satra Apr 21 '21 at 20:46
  • @HarilSatra thank you for replay. after fetching the data I didn't understanding how can i get the all table data into a one json data – Mia Mia Apr 21 '21 at 20:53

1 Answers1

0

I got the Answer

func GetallUser() ([]models.User, error) {
    db := database.DbConnection()
    defer db.Close()
    query := "Select * from user;"
    rows, queryErr := db.Query(query)
    database.Dberror(queryErr)

    defer rows.Close()
    var userrslt []models.User
    for rows.Next() {
        user := models.User{}
        rows.Scan(&user.Id, &user.Username, &user.Password, &user.Firstname)
        userrslt = append(userrslt, user)
    }
    queryErr = rows.Err()
    database.Dberror(queryErr)

    return userrslt, queryErr

}
Mia Mia
  • 143
  • 12