Recount-Server/api.go

76 lines
1.6 KiB
Go
Raw Normal View History

2023-12-30 13:51:59 -08:00
package main
import (
2024-01-11 20:07:47 -08:00
"encoding/json"
"net/http"
2023-12-30 13:51:59 -08:00
2024-01-11 20:07:47 -08:00
//"context"
"fmt"
2023-12-30 13:51:59 -08:00
2024-01-11 20:07:47 -08:00
"github.com/ggicci/httpin"
"github.com/go-chi/chi/v5"
2024-01-01 20:47:34 -08:00
"github.com/rs/zerolog/log"
2023-12-30 13:51:59 -08:00
)
2024-01-11 20:07:47 -08:00
const DEFAULT_RESULT_COUNT = 50
2023-12-30 13:51:59 -08:00
type GetTransactionPaginationInput struct {
2024-01-11 20:07:47 -08:00
ResultCount int `in:"query=result_count"`
PageNum int `in:"query=page_num"`
2023-12-30 13:51:59 -08:00
}
func apiRouter() http.Handler {
2024-01-11 20:07:47 -08:00
r := chi.NewRouter()
//r.Use(ApiLoginRequired)
r.With(
httpin.NewInput(GetTransactionPaginationInput{}),
).Get("/get_transactions", getTransactions)
r.Post("/new_transaction", newTransaction)
return r
2023-12-30 13:51:59 -08:00
}
func getTransactions(w http.ResponseWriter, req *http.Request) {
2024-01-11 20:07:47 -08:00
input := req.Context().Value(httpin.Input).(*GetTransactionPaginationInput)
2023-12-30 13:51:59 -08:00
2024-01-11 20:07:47 -08:00
if input.ResultCount == 0 {
input.ResultCount = DEFAULT_RESULT_COUNT
}
2023-12-30 13:51:59 -08:00
2024-01-11 20:07:47 -08:00
transactions := []Transaction{}
2023-12-30 13:51:59 -08:00
2024-01-11 20:07:47 -08:00
err := db_get_transactions(&transactions, input)
2023-12-31 17:21:09 -08:00
2024-01-11 20:07:47 -08:00
if err != nil {
2023-12-30 13:51:59 -08:00
2024-01-11 20:07:47 -08:00
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))
}
2023-12-30 13:51:59 -08:00
}
func newTransaction(w http.ResponseWriter, req *http.Request) {
2024-01-11 20:07:47 -08:00
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)
2023-12-30 13:51:59 -08:00
}