Recount-Server/api.go
2024-01-11 20:07:47 -08:00

75 lines
1.6 KiB
Go

package main
import (
"encoding/json"
"net/http"
//"context"
"fmt"
"github.com/ggicci/httpin"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
)
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{}
err := db_get_transactions(&transactions, input)
if err != nil {
log.Fatal().
Err(err).
Msg("Fatal error in getTransactions from db_get_transactions")
}
for _, trns := range transactions {
//bytes, err := json.Marshal(trns)
bytes, err := json.MarshalIndent(trns, "", "\t")
if err != nil {
log.Fatal().
Err(err).
Msg("Could not marshal json")
}
fmt.Fprintf(w, string(bytes))
}
}
func newTransaction(w http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var t Transaction
err := decoder.Decode(&t)
if err != nil {
log.Fatal().
Err(err).
Msg("Could not decode incoming post data")
}
//fmt.Fprintf(w, "New transaction created for Account: %d, with an Amount of: %s",
// t.Account, t.Amount)
db_new_transaction(t)
}