package api import ( "net/http" "strings" ) func NewRouter(h *Handler, stream *StreamHandler, auth *AuthHandler) http.Handler { mux := http.NewServeMux() mux.HandleFunc("POST /api/auth/login", auth.Login) mux.HandleFunc("GET /api/auth/verify", auth.Verify) mux.HandleFunc("GET /api/services", h.ListServices) mux.HandleFunc("POST /api/services", h.CreateService) mux.HandleFunc("PUT /api/services/{id}", h.UpdateService) mux.HandleFunc("PATCH /api/services/{id}/toggle", h.ToggleService) mux.HandleFunc("POST /api/services/{id}/test", h.TestService) mux.HandleFunc("DELETE /api/services/{id}", h.DeleteService) mux.HandleFunc("GET /api/services/{id}/history", h.GetHistory) mux.HandleFunc("GET /api/services/{id}/stats", h.GetStats) mux.HandleFunc("GET /api/services/{id}/badge.svg", h.BadgeSVG) mux.HandleFunc("GET /api/active-maintenance", h.GetActiveMaintenance) mux.HandleFunc("GET /api/maintenances", h.ListMaintenances) mux.HandleFunc("POST /api/maintenances", h.CreateMaintenance) mux.HandleFunc("PUT /api/maintenances/{id}", h.UpdateMaintenance) mux.HandleFunc("DELETE /api/maintenances/{id}", h.DeleteMaintenance) mux.Handle("GET /api/stream", stream) return corsMiddleware(auth.Middleware(mux)) } func corsMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { origin := r.Header.Get("Origin") if origin != "" && isAllowedOrigin(origin) { w.Header().Set("Access-Control-Allow-Origin", origin) w.Header().Set("Vary", "Origin") } else { w.Header().Set("Access-Control-Allow-Origin", "*") } w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") w.Header().Set("Access-Control-Max-Age", "86400") if r.Method == http.MethodOptions { w.WriteHeader(http.StatusNoContent) return } next.ServeHTTP(w, r) }) } func isAllowedOrigin(origin string) bool { allowed := []string{ "http://localhost:5173", "http://localhost:4173", "http://127.0.0.1:5173", "http://127.0.0.1:4173", } for _, a := range allowed { if strings.EqualFold(origin, a) { return true } } if strings.HasPrefix(origin, "http://localhost:") { return true } return false }