86 lines
1.8 KiB
Go
86 lines
1.8 KiB
Go
package handlers
|
|
|
|
import (
|
|
"html/template"
|
|
"log/slog"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.maximotejeda.com/maximo/us-dop-api/internal/handlers/api"
|
|
"git.maximotejeda.com/maximo/us-dop-api/internal/ports"
|
|
)
|
|
|
|
var (
|
|
templ template.Template
|
|
)
|
|
|
|
// Mux will mix and match all sub routes
|
|
type Root struct {
|
|
http.ServeMux
|
|
log *slog.Logger
|
|
dolar ports.DolarService
|
|
templates *template.Template
|
|
}
|
|
|
|
func NewRoot(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( 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)
|
|
}
|