You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

59 lines
1.2 KiB

package main
import (
"encoding/json"
"net/http"
"strings"
"github.com/bvinc/go-sqlite-lite/sqlite3"
"github.com/sporestack/settlers"
)
func balance(token string, db *sqlite3.Conn) (amount uint64, userErr, err error) {
if userErr = settlers.ValidateToken(token); userErr != nil {
return
}
statement, err := db.Prepare("SELECT balance FROM balances WHERE combined_token = ?", token)
if err != nil {
return
}
defer statement.Close()
hasRow, err := statement.Step()
if err != nil {
return
}
if !hasRow {
userErr = settlers.ErrorTokenNotEnabled
return
}
// sqlite3 only supports signed integers
var signedAmount int64
if err = statement.Scan(&signedAmount); err != nil {
return
}
amount = uint64(signedAmount)
return
}
func httpBalance(w http.ResponseWriter, r *http.Request, db *sqlite3.Conn) {
defer r.Body.Close()
pathParts := strings.Split(r.URL.Path, "/")
token := pathParts[len(pathParts)-1]
amount, userErr, err := balance(token, db)
if err != nil {
httpHandle500(w, err)
return
}
if userErr != nil {
httpHandle400(w, userErr)
return
}
responseStruct := settlers.BalanceResponse{Amount: amount}
err = json.NewEncoder(w).Encode(responseStruct)
if err != nil {
httpHandle500(w, err)
return
}
return
}