package main import ( "net/http" "encoding/json" //"context" "fmt" "log" _ "github.com/lib/pq" "github.com/jmoiron/sqlx" "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) { db, err := sqlx.Connect("postgres", DB_CONNECTION_STRING) if err != nil { log.Fatal(err) } defer db.Close() input := req.Context().Value(httpin.Input).(*GetTransactionPaginationInput) if input.ResultCount == 0 { input.ResultCount = DEFAULT_RESULT_COUNT } transactions := []Transaction{} err = db.Select(&transactions, "SELECT trns_id, trns_amount, trns_description, " + "trns_account, trns_bucket, trns_date " + "FROM rcnt.transactions ORDER BY trns_id DESC " + fmt.Sprintf("OFFSET %d ROWS FETCH NEXT %d ROWS ONLY", input.PageNum, input.ResultCount)) 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) }