Recount-Server/api.go

70 lines
1.6 KiB
Go
Raw Normal View History

2023-12-30 13:51:59 -08:00
package main
import (
"net/http"
"encoding/json"
//"context"
"fmt"
"log"
"github.com/go-chi/chi/v5"
"github.com/ggicci/httpin"
)
const DEFAULT_RESULT_COUNT = 50;
type GetTransactionPaginationInput struct {
ResultCount int `in:"query=result_count"`
PageNum int `in:"query=page_num"`
}
func apiRouter() http.Handler {
r := chi.NewRouter()
//r.Use(ApiLoginRequired)
r.With(
httpin.NewInput(GetTransactionPaginationInput{}),
).Get("/get_transactions", getTransactions)
r.Post("/new_transaction", newTransaction)
return r
}
func getTransactions(w http.ResponseWriter, req *http.Request) {
input := req.Context().Value(httpin.Input).(*GetTransactionPaginationInput)
if input.ResultCount == 0 {
input.ResultCount = DEFAULT_RESULT_COUNT
}
transactions := []Transaction{}
2023-12-31 17:21:09 -08:00
err := db_get_transactions(&transactions, input)
if err != nil {
log.Print("Fatal error in getTransactions from db_get_transactions")
log.Fatal(err)
}
2023-12-30 13:51:59 -08:00
for _, trns := range transactions {
//bytes, err := json.Marshal(trns)
bytes, err := json.MarshalIndent(trns, "", "\t")
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(w, string(bytes))
}
}
func newTransaction(w http.ResponseWriter, req *http.Request) {
2023-12-30 14:10:41 -08:00
decoder := json.NewDecoder(req.Body)
var t Transaction
err := decoder.Decode(&t)
2023-12-30 13:51:59 -08:00
if err != nil {
log.Fatal(err)
}
2023-12-31 17:21:09 -08:00
//fmt.Fprintf(w, "New transaction created for Account: %d, with an Amount of: %s",
// t.Account, t.Amount)
db_new_transaction(t)
2023-12-30 13:51:59 -08:00
}