Files
atlas/internal/httpapp/app.go
othman.suseno ed96137bad
Some checks failed
CI / test-build (push) Failing after 1m0s
adding snapshot function
2025-12-14 23:17:26 +07:00

97 lines
2.1 KiB
Go

package httpapp
import (
"fmt"
"html/template"
"net/http"
"path/filepath"
"time"
"gitea.avt.data-center.id/othman.suseno/atlas/internal/job"
"gitea.avt.data-center.id/othman.suseno/atlas/internal/snapshot"
"gitea.avt.data-center.id/othman.suseno/atlas/internal/zfs"
)
type Config struct {
Addr string
TemplatesDir string
StaticDir string
}
type App struct {
cfg Config
tmpl *template.Template
mux *http.ServeMux
zfs *zfs.Service
snapshotPolicy *snapshot.PolicyStore
jobManager *job.Manager
scheduler *snapshot.Scheduler
}
func New(cfg Config) (*App, error) {
if cfg.TemplatesDir == "" {
cfg.TemplatesDir = "web/templates"
}
if cfg.StaticDir == "" {
cfg.StaticDir = "web/static"
}
tmpl, err := parseTemplates(cfg.TemplatesDir)
if err != nil {
return nil, err
}
zfsService := zfs.New()
policyStore := snapshot.NewPolicyStore()
jobMgr := job.NewManager()
scheduler := snapshot.NewScheduler(policyStore, zfsService, jobMgr)
a := &App{
cfg: cfg,
tmpl: tmpl,
mux: http.NewServeMux(),
zfs: zfsService,
snapshotPolicy: policyStore,
jobManager: jobMgr,
scheduler: scheduler,
}
// Start snapshot scheduler (runs every 15 minutes)
scheduler.Start(15 * time.Minute)
a.routes()
return a, nil
}
func (a *App) Router() http.Handler {
// Wrap the mux with basic middleware chain
return requestID(logging(a.mux))
}
// StopScheduler stops the snapshot scheduler (for graceful shutdown)
func (a *App) StopScheduler() {
if a.scheduler != nil {
a.scheduler.Stop()
}
}
// routes() is now in routes.go
func parseTemplates(dir string) (*template.Template, error) {
pattern := filepath.Join(dir, "*.html")
files, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
if len(files) == 0 {
return nil, fmt.Errorf("no templates found at %s", pattern)
}
funcs := template.FuncMap{
"nowRFC3339": func() string { return time.Now().Format(time.RFC3339) },
}
t := template.New("root").Funcs(funcs)
return t.ParseFiles(files...)
}