package recipe import ( "encoding/json" "log/slog" "net/http" "github.com/food-ai/backend/internal/infra/middleware" "github.com/go-chi/chi/v5" ) // Handler handles HTTP requests for recipes. type Handler struct { repo *Repository } // NewHandler creates a new Handler. func NewHandler(repo *Repository) *Handler { return &Handler{repo: repo} } // GetByID handles GET /recipes/{id}. func (h *Handler) GetByID(w http.ResponseWriter, r *http.Request) { userID := middleware.UserIDFromCtx(r.Context()) if userID == "" { writeErrorJSON(w, http.StatusUnauthorized, "unauthorized") return } id := chi.URLParam(r, "id") rec, err := h.repo.GetByID(r.Context(), id) if err != nil { slog.Error("get recipe", "id", id, "err", err) writeErrorJSON(w, http.StatusInternalServerError, "failed to get recipe") return } if rec == nil { writeErrorJSON(w, http.StatusNotFound, "recipe not found") return } writeJSON(w, http.StatusOK, rec) } type errorResponse struct { Error string `json:"error"` } func writeErrorJSON(w http.ResponseWriter, status int, msg string) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(errorResponse{Error: msg}) } func writeJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) }