Files
2026-01-19 19:50:09 +01:00

56 lines
1.5 KiB
Go

package api
import (
"net/http"
"strings"
"training-tracker/internal/storage"
)
// Router sets up and returns the HTTP router
type Router struct {
exerciseHandler *ExerciseHandler
planHandler *PlanHandler
sessionHandler *SessionHandler
}
// NewRouter creates a new router with all handlers
func NewRouter(db *storage.DB) *Router {
exerciseRepo := storage.NewExerciseRepository(db)
planRepo := storage.NewPlanRepository(db)
sessionRepo := storage.NewSessionRepository(db)
return &Router{
exerciseHandler: NewExerciseHandler(exerciseRepo),
planHandler: NewPlanHandler(planRepo),
sessionHandler: NewSessionHandler(sessionRepo),
}
}
// ServeHTTP implements http.Handler
func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Enable CORS
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
path := r.URL.Path
switch {
case strings.HasPrefix(path, "/api/exercises"):
router.exerciseHandler.ServeHTTP(w, r)
case strings.HasPrefix(path, "/api/plans"):
router.planHandler.ServeHTTP(w, r)
case strings.HasPrefix(path, "/api/sessions"):
router.sessionHandler.ServeHTTP(w, r)
case path == "/api/health":
respondJSON(w, http.StatusOK, map[string]string{"status": "ok"})
default:
respondError(w, http.StatusNotFound, "not found")
}
}