Show whether request was successful or not via json

This commit is contained in:
raul 2024-12-11 12:36:02 +01:00
parent e13e9e2019
commit b673009635
Signed by: raul
GPG Key ID: C1AA797073F17129
2 changed files with 20 additions and 10 deletions

View File

@ -143,46 +143,51 @@ func createUser(c *gin.Context) {
c.String(http.StatusOK, "Success!\n")
}
func setResponse(content any, success bool) response {
msg := response{Contents: content, Success: success}
return msg
}
func getUser(c *gin.Context) {
id := c.Param("userid")
user := user{}
dynStmt := `SELECT id_alumno,nombre,apellido1,apellido2,email FROM alumnos WHERE id_alumno = $1`
err := db.QueryRow(dynStmt, id).Scan(&user.Id, &user.Name, &user.Surname1, &user.Surname2, &user.Email)
dynStmt := `SELECT id_usuario,nombre,apellido1,apellido2,email,rol FROM usuarios WHERE id_usuario = $1`
err := db.QueryRow(dynStmt, id).Scan(&user.Id, &user.Name, &user.Surname1, &user.Surname2, &user.Email, &user.AccountType)
if err != nil {
if err == sql.ErrNoRows {
c.String(http.StatusNotFound, "User not found")
c.IndentedJSON(http.StatusNotFound, setResponse("User not found", false))
return
}
e := fmt.Sprintf("SOMETHING BAD HAPPENED QUERYING THE DATABASE: %v\n", err)
log.Print(e)
c.String(http.StatusInternalServerError, e)
c.IndentedJSON(http.StatusInternalServerError, setResponse(e, false))
return
}
c.IndentedJSON(http.StatusOK, user)
c.IndentedJSON(http.StatusOK, setResponse(user, true))
}
func getUsers(c *gin.Context) {
users := []user{}
rows, err := db.Query("SELECT id_alumno,nombre,apellido1,apellido2,email FROM alumnos")
rows, err := db.Query("SELECT id_usuario,nombre,apellido1,apellido2,email,rol FROM usuarios")
if err != nil {
e := fmt.Sprintf("SOMETHING BAD HAPPENED QUERYING THE DATABASE: %v\n", err)
log.Print(e)
c.String(http.StatusInternalServerError, e)
c.IndentedJSON(http.StatusInternalServerError, setResponse(e, false))
return
}
defer rows.Close()
for rows.Next() {
user := user{}
err = rows.Scan(&user.Id, &user.Name, &user.Surname1, &user.Surname2, &user.Email)
err = rows.Scan(&user.Id, &user.Name, &user.Surname1, &user.Surname2, &user.Email, &user.AccountType)
if err != nil {
e := fmt.Sprintf("SOMETHING BAD HAPPENED SCANNING THE ROWS: %v\n", err)
log.Print(e)
c.String(http.StatusInternalServerError, e)
c.IndentedJSON(http.StatusInternalServerError, setResponse(e, false))
return
}
users = append(users, user)
}
c.IndentedJSON(http.StatusOK, users)
c.IndentedJSON(http.StatusOK, setResponse(users, true))
}
func helloWorld(c *gin.Context) {

View File

@ -9,3 +9,8 @@ type user struct {
Password string `json:"password"`
AccountType string `json:"type"`
}
type response struct {
Contents any `json:"contents"`
Success bool `json:"success"`
}