package web import ( "database/sql" "html/template" "net/http" "bytes" "context" "fmt" "time" "github.com/a-h/templ" "github.com/go-chi/chi/v5" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "nickiel.net/recount_server/types" ) type TemplateState struct { InnerHtml template.HTML ActivePage string } const TemplateDir = "./web/templates/" func SetLogLevel(level zerolog.Level) { zerolog.SetGlobalLevel(level) } func WebRouter() http.Handler { r := chi.NewRouter() r.Get("/", getIndex) r.Get("/web/transaction_table_rows", getTransactions) r.Get("/hello", getHello) r.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("web/static/")))) return r } //for name, values := range req.Header { // Loop over all values for the name. // for _, value := range values { // log.Debug().Msg(name + " " + value); // } // } func renderFullPage(w http.ResponseWriter, c templ.Component, pageName string) { var buf bytes.Buffer // Render the provided templ component err := c.Render(context.Background(), &buf) if err != nil { log.Fatal().Err(err).Msg("Fatal error reading hello template"); } // get the index template index, err := template.ParseFiles(TemplateDir + "index.html") if err != nil { log.Fatal(). Err(err). Msg("Fatal error reading index template") } // Inject the templ component html into the index template err = index.Execute(w, TemplateState{ InnerHtml: template.HTML(buf.String()), ActivePage: pageName, }); if err != nil { log.Fatal().Err(err).Msg("Fatal error reading hello template"); } } func getIndex(w http.ResponseWriter, req *http.Request) { component := dashboard(); _, ok := req.Header["Hx-Request"] if ok { err := component.Render(context.Background(), w); if err != nil { log.Fatal().Err(err).Msg("Couldn't render dashboard templ template"); } } else { renderFullPage(w, component, "index"); } } func getHello(w http.ResponseWriter, req *http.Request) { component := hello("Nick") _, ok := req.Header["Hx-Request"] if ok { err := component.Render(context.Background(), w); if err != nil { log.Fatal().Err(err).Msg("Couldn't render dashboard templ template"); } }else { renderFullPage(w, component, "hello"); } } const DEFAULT_RESULT_COUNT = 20; func getTransactions(w http.ResponseWriter, req *http.Request) { transactions := make([]types.HumanLegibleTransaction, 10) // Populate the slice with dummy data (you can replace this with your actual data) for i := 10; i > 0; i-- { transaction := types.HumanLegibleTransaction{ Id: i, Amount: fmt.Sprintf("%d.00", (i+1)*100), Description: sql.NullString{String: fmt.Sprintf("Transaction %d", i+1), Valid: true}, AccountName: sql.NullString{String: "Savings", Valid: true}, Account: 123, Bucket: sql.NullInt64{Int64: int64(i + 100), Valid: true}, BucketName: sql.NullString{String: fmt.Sprintf("Bucket %d", i+1), Valid: true}, Date: time.Now(), } transactions[10 - i] = transaction } component := transaction_rows(&transactions); component.Render(context.Background(), w); }