69 lines
1.6 KiB
Go
69 lines
1.6 KiB
Go
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{}
|
|
|
|
err := db_get_transactions(&transactions, input)
|
|
|
|
if err != nil {
|
|
log.Print("Fatal error in getTransactions from db_get_transactions")
|
|
log.Fatal(err)
|
|
}
|
|
|
|
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) {
|
|
decoder := json.NewDecoder(req.Body)
|
|
var t Transaction
|
|
err := decoder.Decode(&t)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
//fmt.Fprintf(w, "New transaction created for Account: %d, with an Amount of: %s",
|
|
// t.Account, t.Amount)
|
|
db_new_transaction(t)
|
|
}
|