restgogo-fiber

How to have a consistent response format in go-fiber


i have a query inside of an endpoint right here,

query := `SELECT * FROM "user" WHERE username = $1`
    row := db.QueryRow(query, user.Username)

    var (
        usn        string
        pass       string
        created_at string
        id         int
    )

    // binds the above variables to "row" that is returned by "db.QueryRow"
    // "row.Scan" will also release the connection
    if err := row.Scan(&usn, &pass, &created_at, &id); err != nil {
        return c.Status(500).JSON(fiber.Map{
            "error": err,
        })
    }

    return c.JSON(fiber.Map{
        "username":   usn,
        "password":   pass,
        "created_at": created_at,
        "id":         id,
    })

when i hit this endpoint, the reponse is,

{
    "created_at": "timestamp",
    "id": 3,
    "password": "123",
    "username": "bro"
}

how do i make it so that the response is just like how i return it, which would be,

{
    "username":   "bro",
    "password":   "123",
    "created_at": "timestamp",
    "id":         3,
}

Solution

  • You can use struct instead of map if you want to make sure the order. Map does not preserve the order of keys.

    type UserResponse struct {
        Username  string `json:"username"`
        Password  string `json:"password"`
        CreatedAt string `json:"created_at"`
        ID        int    `json:"id"`
    }
    
    .... your code
    
    response := UserResponse{
        Username:  usn,
        Password:  pass,
        CreatedAt: created_at,
        ID:        id,
    }
    
    return c.JSON(response)