ran gofmt

This commit is contained in:
Nickiel12 2024-01-11 20:07:47 -08:00
parent d5fc3d8d23
commit da14c059c1
5 changed files with 219 additions and 204 deletions

98
api.go
View file

@ -1,75 +1,75 @@
package main package main
import ( import (
"net/http" "encoding/json"
"encoding/json" "net/http"
//"context" //"context"
"fmt" "fmt"
"github.com/go-chi/chi/v5" "github.com/ggicci/httpin"
"github.com/ggicci/httpin" "github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
) )
const DEFAULT_RESULT_COUNT = 50; const DEFAULT_RESULT_COUNT = 50
type GetTransactionPaginationInput struct { type GetTransactionPaginationInput struct {
ResultCount int `in:"query=result_count"` ResultCount int `in:"query=result_count"`
PageNum int `in:"query=page_num"` PageNum int `in:"query=page_num"`
} }
func apiRouter() http.Handler { func apiRouter() http.Handler {
r := chi.NewRouter() r := chi.NewRouter()
//r.Use(ApiLoginRequired) //r.Use(ApiLoginRequired)
r.With( r.With(
httpin.NewInput(GetTransactionPaginationInput{}), httpin.NewInput(GetTransactionPaginationInput{}),
).Get("/get_transactions", getTransactions) ).Get("/get_transactions", getTransactions)
r.Post("/new_transaction", newTransaction) r.Post("/new_transaction", newTransaction)
return r return r
} }
func getTransactions(w http.ResponseWriter, req *http.Request) { func getTransactions(w http.ResponseWriter, req *http.Request) {
input := req.Context().Value(httpin.Input).(*GetTransactionPaginationInput) input := req.Context().Value(httpin.Input).(*GetTransactionPaginationInput)
if input.ResultCount == 0 { if input.ResultCount == 0 {
input.ResultCount = DEFAULT_RESULT_COUNT input.ResultCount = DEFAULT_RESULT_COUNT
} }
transactions := []Transaction{} transactions := []Transaction{}
err := db_get_transactions(&transactions, input) err := db_get_transactions(&transactions, input)
if err != nil { if err != nil {
log.Fatal().
Err(err).
Msg("Fatal error in getTransactions from db_get_transactions")
}
for _, trns := range transactions { log.Fatal().
//bytes, err := json.Marshal(trns) Err(err).
bytes, err := json.MarshalIndent(trns, "", "\t") Msg("Fatal error in getTransactions from db_get_transactions")
if err != nil { }
log.Fatal().
Err(err). for _, trns := range transactions {
Msg("Could not marshal json") //bytes, err := json.Marshal(trns)
} bytes, err := json.MarshalIndent(trns, "", "\t")
fmt.Fprintf(w, string(bytes)) 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) { func newTransaction(w http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body) decoder := json.NewDecoder(req.Body)
var t Transaction var t Transaction
err := decoder.Decode(&t) err := decoder.Decode(&t)
if err != nil { if err != nil {
log.Fatal(). log.Fatal().
Err(err). Err(err).
Msg("Could not decode incoming post data") Msg("Could not decode incoming post data")
} }
//fmt.Fprintf(w, "New transaction created for Account: %d, with an Amount of: %s", //fmt.Fprintf(w, "New transaction created for Account: %d, with an Amount of: %s",
// t.Account, t.Amount) // t.Account, t.Amount)
db_new_transaction(t) db_new_transaction(t)
} }

86
db.go
View file

@ -1,58 +1,58 @@
package main package main
import ( import (
"fmt" "fmt"
_ "github.com/lib/pq" "github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3" _ "github.com/lib/pq"
"github.com/jmoiron/sqlx" _ "github.com/mattn/go-sqlite3"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
) )
func db_get_transactions(transactions *[]Transaction,r *GetTransactionPaginationInput) (error) { func db_get_transactions(transactions *[]Transaction, r *GetTransactionPaginationInput) error {
db, err := sqlx.Connect(DB_TYPE, DB_CONNECTION_STRING) db, err := sqlx.Connect(DB_TYPE, DB_CONNECTION_STRING)
if err != nil { if err != nil {
log.Fatal(). log.Fatal().
Err(err). Err(err).
Msg("Fatal error in db_get_transactions\nCannot connect to server") Msg("Fatal error in db_get_transactions\nCannot connect to server")
} }
defer db.Close() defer db.Close()
err = db.Select(transactions, err = db.Select(transactions,
"SELECT trns_id, trns_amount, trns_description, " + "SELECT trns_id, trns_amount, trns_description, "+
"trns_account, trns_bucket, trns_date " + "trns_account, trns_bucket, trns_date "+
fmt.Sprintf("FROM %stransactions ORDER BY trns_id DESC ", DB_SCHEMA) + fmt.Sprintf("FROM %stransactions ORDER BY trns_id DESC ", DB_SCHEMA)+
fmt.Sprintf("LIMIT %d OFFSET %d", fmt.Sprintf("LIMIT %d OFFSET %d",
r.ResultCount, r.PageNum * r.ResultCount )) r.ResultCount, r.PageNum*r.ResultCount))
if err != nil { if err != nil {
return err return err
} }
return nil return nil
} }
func db_new_transaction(transaction Transaction) (error) { func db_new_transaction(transaction Transaction) error {
db, err := sqlx.Connect(DB_TYPE, DB_CONNECTION_STRING) db, err := sqlx.Connect(DB_TYPE, DB_CONNECTION_STRING)
if err != nil { if err != nil {
log.Info() log.Info()
log.Fatal(). log.Fatal().
Err(err). Err(err).
Msg("Fatal error in db_get_transactions\nCannot connect to server") Msg("Fatal error in db_get_transactions\nCannot connect to server")
} }
defer db.Close() defer db.Close()
log.Debug().Msgf("%#v", transaction) log.Debug().Msgf("%#v", transaction)
_, err = db.NamedExec( _, err = db.NamedExec(
fmt.Sprintf("INSERT INTO %stransactions", DB_SCHEMA) + fmt.Sprintf("INSERT INTO %stransactions", DB_SCHEMA)+
"(trns_amount, trns_description, trns_account, trns_bucket, trns_date)" + "(trns_amount, trns_description, trns_account, trns_bucket, trns_date)"+
"VALUES (:trns_amount, :trns_description, :trns_account, :trns_bucket, :trns_date)", "VALUES (:trns_amount, :trns_description, :trns_account, :trns_bucket, :trns_date)",
transaction) transaction)
if err != nil { if err != nil {
log.Fatal(). log.Fatal().
Err(err). Err(err).
Msg("Could not exec insert db query") Msg("Could not exec insert db query")
} }
return nil return nil
} }

110
main.go
View file

@ -2,6 +2,7 @@ package main
import ( import (
"nickiel.net/recount_server/tests" "nickiel.net/recount_server/tests"
"nickiel.net/recount_server/web"
"database/sql" "database/sql"
"net/http" "net/http"
@ -25,80 +26,79 @@ var DB_CONNECTION_STRING string = "user=rcntuser password=Devel@pmentPa$$w0rd ho
// "json:"json_code_name,omitempty"" (omit empty) // "json:"json_code_name,omitempty"" (omit empty)
// if you use `json:"-"` it doesn't encode it // if you use `json:"-"` it doesn't encode it
type Transaction struct { type Transaction struct {
Id int `db:"trns_id" json:"Id"` Id int `db:"trns_id" json:"Id"`
Amount string `db:"trns_amount" json:"Amount"` Amount string `db:"trns_amount" json:"Amount"`
Description sql.NullString `db:"trns_description" json:"Description"` Description sql.NullString `db:"trns_description" json:"Description"`
Account int `db:"trns_account" json:"Account"` Account int `db:"trns_account" json:"Account"`
Bucket sql.NullInt64 `db:"trns_bucket" json:"Bucket"` Bucket sql.NullInt64 `db:"trns_bucket" json:"Bucket"`
Date time.Time `db:"trns_date" json:"TransactionDate"` Date time.Time `db:"trns_date" json:"TransactionDate"`
} }
func hello(w http.ResponseWriter, req *http.Request) { func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "hello\n") fmt.Fprintf(w, "hello\n")
} }
func headers(w http.ResponseWriter, req *http.Request) { func headers(w http.ResponseWriter, req *http.Request) {
for name, headers := range req.Header { for name, headers := range req.Header {
for _, h := range headers { for _, h := range headers {
fmt.Fprintf(w, "%v: %v\n", name, h) fmt.Fprintf(w, "%v: %v\n", name, h)
} }
} }
} }
func main() { func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
zerolog.SetGlobalLevel(zerolog.InfoLevel) zerolog.SetGlobalLevel(zerolog.InfoLevel)
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
var debugFlag = flag.Bool("d", false, "whether to enable debug mode") var debugFlag = flag.Bool("d", false, "whether to enable debug mode")
var traceFlag = flag.Bool("t", false, "whether to trace logging") var traceFlag = flag.Bool("t", false, "whether to trace logging")
flag.Parse() flag.Parse()
if *traceFlag { if *traceFlag {
zerolog.SetGlobalLevel(zerolog.TraceLevel) zerolog.SetGlobalLevel(zerolog.TraceLevel)
log.Debug().Msg("Enabling trace level debugging") log.Debug().Msg("Enabling trace level debugging")
} }
if *debugFlag { if *debugFlag {
if !*traceFlag { if !*traceFlag {
zerolog.SetGlobalLevel(zerolog.DebugLevel) zerolog.SetGlobalLevel(zerolog.DebugLevel)
} }
log.Debug().Msg("Is debugging") log.Debug().Msg("Is debugging")
DB_TYPE = "sqlite3" DB_TYPE = "sqlite3"
DB_SCHEMA = "" DB_SCHEMA = ""
DB_CONNECTION_STRING = "test.db" DB_CONNECTION_STRING = "test.db"
debug_mode.Init_testdb(DB_TYPE, DB_CONNECTION_STRING) debug_mode.Init_testdb(DB_TYPE, DB_CONNECTION_STRING)
} }
debug_mode.SetLogLevel(zerolog.GlobalLevel())
debug_mode.SetLogLevel(zerolog.GlobalLevel()) log.Info().Msg("starting server")
log.Info().Msg("starting server") r := chi.NewRouter()
r := chi.NewRouter() // A good base middleware stack
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Recoverer)
r.Use(middleware.Logger)
// A good base middleware stack // Set a timeout value on the request context (ctx), that will signal
r.Use(middleware.RequestID) // through ctx.Done() that the request has timed out and further
r.Use(middleware.RealIP) // processing should be stopped.
r.Use(middleware.Recoverer) //r.Use(middleware.Timeout(60 * time.Second))
r.Use(middleware.Logger)
// Set a timeout value on the request context (ctx), that will signal r.Get("/headers", headers)
// through ctx.Done() that the request has timed out and further r.Mount("/", web.WebRouter())
// processing should be stopped. r.Mount("/api", apiRouter())
//r.Use(middleware.Timeout(60 * time.Second))
r.Get("/", hello) err := http.ListenAndServe(":8090", r)
r.Get("/headers", headers) if err != nil {
r.Mount("/api", apiRouter()) log.Fatal().
Err(err).
Msg("Could not open server connection")
}
err := http.ListenAndServe(":8090", r) //fmt.Println("Hello World")
if err != nil {
log.Fatal().
Err(err).
Msg("Could not open server connection")
}
//fmt.Println("Hello World")
} }

View file

@ -1,9 +1,9 @@
package debug_mode package debug_mode
import ( import (
"os"
"encoding/json"
"database/sql" "database/sql"
"encoding/json"
"os"
"time" "time"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
@ -13,50 +13,50 @@ import (
) )
type Transaction struct { type Transaction struct {
Id int `db:"trns_id" json:"Id"` Id int `db:"trns_id" json:"Id"`
Amount string `db:"trns_amount" json:"Amount"` Amount string `db:"trns_amount" json:"Amount"`
Description sql.NullString `db:"trns_description" json:"Description"` Description sql.NullString `db:"trns_description" json:"Description"`
Account int `db:"trns_account" json:"Account"` Account int `db:"trns_account" json:"Account"`
Bucket sql.NullInt64 `db:"trns_bucket" json:"Bucket"` Bucket sql.NullInt64 `db:"trns_bucket" json:"Bucket"`
Date time.Time `db:"trns_date" json:"TransactionDate"` Date time.Time `db:"trns_date" json:"TransactionDate"`
} }
func SetLogLevel(level zerolog.Level) { func SetLogLevel(level zerolog.Level) {
zerolog.SetGlobalLevel(level) zerolog.SetGlobalLevel(level)
} }
func Init_testdb(DB_TYPE string, DB_CONNECTION_STRING string) { func Init_testdb(DB_TYPE string, DB_CONNECTION_STRING string) {
cwd, err := os.Getwd() cwd, err := os.Getwd()
if err != nil { if err != nil {
log.Fatal().Err(err).Msg("Could not get current working directory") log.Fatal().Err(err).Msg("Could not get current working directory")
} else { } else {
log.Trace().Msgf("Currect working directory is: %s", cwd) log.Trace().Msgf("Currect working directory is: %s", cwd)
} }
_, err = os.Stat(cwd + DB_CONNECTION_STRING) _, err = os.Stat(cwd + DB_CONNECTION_STRING)
if err != nil { if err != nil {
log.Debug().Msg("Found existing test.db file. Attempting to delete") log.Debug().Msg("Found existing test.db file. Attempting to delete")
err = os.Remove(DB_CONNECTION_STRING) err = os.Remove(DB_CONNECTION_STRING)
if err != nil { if err != nil {
log.Fatal().Err(err).Msg("Failed to delete testing db") log.Fatal().Err(err).Msg("Failed to delete testing db")
} else { } else {
log.Debug().Msg("Deleted test.db file successfully") log.Debug().Msg("Deleted test.db file successfully")
} }
} else { } else {
log.Debug().Msg("No existing test.db file found") log.Debug().Msg("No existing test.db file found")
} }
db, err := sqlx.Connect(DB_TYPE, DB_CONNECTION_STRING)
if err != nil {
log.Fatal().
Err(err).
Msg("Couldn't open test db")
}
defer db.Close() db, err := sqlx.Connect(DB_TYPE, DB_CONNECTION_STRING)
if err != nil {
log.Fatal().
Err(err).
Msg("Couldn't open test db")
}
init_sql := ` defer db.Close()
init_sql := `
CREATE TABLE accounts ( CREATE TABLE accounts (
acnt_id Integer PRIMARY KEY, acnt_id Integer PRIMARY KEY,
acnt_dsply_name varchar(50) NOT NULL, acnt_dsply_name varchar(50) NOT NULL,
@ -116,18 +116,18 @@ INSERT INTO transactions (trns_amount, trns_description, trns_account, trns_buck
("50.00", "Money", 1, 1, "2023-11-10"); ("50.00", "Money", 1, 1, "2023-11-10");
` `
tx := db.MustBegin() tx := db.MustBegin()
tx.MustExec(init_sql) tx.MustExec(init_sql)
err = tx.Commit() err = tx.Commit()
if err != nil { if err != nil {
log.Fatal(). log.Fatal().
Err(err). Err(err).
Msg("Could not commit transaction") Msg("Could not commit transaction")
} }
jsonExample := `{ jsonExample := `{
"Id": 3, "Id": 3,
"Amount": "100", "Amount": "100",
"Description": { "Description": {
@ -142,20 +142,18 @@ INSERT INTO transactions (trns_amount, trns_description, trns_account, trns_buck
"TransactionDate": "2023-11-11T00:00:00Z" "TransactionDate": "2023-11-11T00:00:00Z"
}` }`
var trns Transaction = Transaction{} var trns Transaction = Transaction{}
err = json.Unmarshal([]byte(jsonExample), &trns) err = json.Unmarshal([]byte(jsonExample), &trns)
if err != nil { if err != nil {
log.Fatal().Err(err).Msg("could not unmarshal") log.Fatal().Err(err).Msg("could not unmarshal")
} }
_, err = db.NamedExec("INSERT INTO transactions" + _, err = db.NamedExec("INSERT INTO transactions"+
"(trns_amount, trns_description, trns_account, trns_bucket, trns_date)" + "(trns_amount, trns_description, trns_account, trns_bucket, trns_date)"+
"VALUES (:trns_amount, :trns_description, :trns_account, :trns_bucket, :trns_date)", "VALUES (:trns_amount, :trns_description, :trns_account, :trns_bucket, :trns_date)",
trns) trns)
log.Debug().Msg("Test database initialized")
log.Debug().Msg("Test database initialized")
} }

17
web/router.go Normal file
View file

@ -0,0 +1,17 @@
package web
import (
"net/http"
"github.com/go-chi/chi/v5"
)
func WebRouter() http.Handler {
r := chi.NewRouter()
r.Get("/", getIndex)
return r
}
func getIndex(w http.ResponseWriter, req *http.Request) {
}