I'm learning to create HTTP API's,
I'm creating a dummy API credit system, as that's what I'm interested in specifically.
This is what i came up with: (I'm using PQ Driver)
if !dummy.creds <= 0 {
c.JSON(404, gin.H{
"success": false,
"message": "No Credits!",
})
return
}
However, let's say i edit the SQL table to say 50 Credits, How do subtract 1 credit everytime the dummy API is queried?
So for example, if i Query the API and it returns the successful dummy data (in JSON) from the SQL table, how can i subtract one credit, so that i only have 49 credits, then 48, 47, 46, etc.
UPDATE: This is what i came up with
_, err := db.Exec("UPDATE dummy SET creds = -1 WHERE email = $1")
if err != nil {
log.Fatal(err)
}
Instead of working, it fails to do anything.
What am i doing wrong?
Any answers & knowledge into this would be amazing!
Thanks!
As posted by @seva
I believe the question is about returning consistent results. It's not about go then. It's about database. Search "optimistic locking" vs "pessimistic locking", "select for update" etc. Here is also a basic (but good) introduction to working with databases in go (if you need it): go-database-sql.org/index.html