package handlers import ( "html/template" "log/slog" "net/http" "strings" "time" "github.com/maximotejeda/us_dop_api/handlers/api" "github.com/maximotejeda/us_dop_api/ports" "github.com/maximotejeda/us_dop_db/db" ) var ( templ template.Template ) // Mux will mix and match all sub routes type Root struct { http.ServeMux db *db.DB log *slog.Logger dolar ports.DolarService templates *template.Template } func NewRoot(dbe *db.DB, dolar ports.DolarService, log *slog.Logger, files []string) *Root { funcMap := template.FuncMap{ "add": add[float64], "div": div, "mult": mult[float64], "fdate": fdate, "replace": replace, } templ = *template.Must(template.New("").Funcs(funcMap).ParseFiles(files...)) r := Root{ log: log, dolar: dolar, templates: &templ, } r.HandleFunc("/{$}", func(w http.ResponseWriter, r *http.Request) { templ.ExecuteTemplate(w, "index", nil) //w.Write([]byte("{'status': 'ok'}")) }) inst := api.NewApiHandler(dbe, dolar, log, templ) r.Handle("GET /api/{inst}/", inst) r.Handle("POST /api/instituciones/history", inst) r.Handle("GET /api/latest/{inst}", inst) r.Handle("POST /api/control/", inst) r.HandleFunc("/api/{$}", http.NotFound) // telegram r.HandleFunc("/telegram/{$}", func(w http.ResponseWriter, r *http.Request) { templ.ExecuteTemplate(w, "index", nil) //w.Write([]byte("{'status': 'ok'}")) }) return &r } func add[v float64 | int](a, b v) v { return a + b } func div(a float64, b int) float64 { if a == 0 || b == 0 { return 0 } return a / float64(b) } func mult[v float64 | int](a, b v) v { return a * b } func fdate(t time.Time) string { return t.Format("15 02-01-06") } // replace // replace string func replace(rep, torep, original string) string { return strings.ReplaceAll(original, rep, torep) }