package web import ( "html/template" "net/http" "strconv" "bytes" "context" "github.com/a-h/templ" "github.com/go-chi/chi/v5" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) 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("/", getDashboard) r.Get("/transactions", getTransactionsPage) r.Get("/components/account_summaries", getAccountSummaries) r.Get("/components/right_panel_quick_access", getRightPanelQuickAccess) r.Get("/components/data/transaction_table_rows", getTransactionsRows) r.Get("/components/data/expenditure_chart", getExpenditureChart) r.Get("/components/data/account_summary/{accountID}", getAccountSummaryChart) r.Get("/components/data/transaction_quick_access", getTransactionQuickAccessEntries) 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 getDashboard(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, "Dashboard"); } } func getTransactionsPage(w http.ResponseWriter, req *http.Request) { accounts := make([]string, 10); for i := 0; i < 10; i++ { accounts[i] = strconv.Itoa(i) + " Account"; } component := transactions_page(1, &accounts); _, ok := req.Header["Hx-Request"] if ok { err := component.Render(context.Background(), w); if err != nil { log.Fatal().Err(err).Msg("Couldn't render transactions templ template"); } } else { renderFullPage(w, component, "Transactions") } }