Move all business-logic packages from internal/ root into internal/domain/: auth, cuisine, diary, dish, home, ingredient, language, menu, product, recipe, recognition, recommendation, savedrecipe, tag, units, user Rename model.go → entity.go in packages that hold domain entities: diary, dish, home, ingredient, menu, product, recipe, savedrecipe, user Update all import paths accordingly (adapters, infra/server, cmd/server, tests). No logic changes. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
59 lines
1.4 KiB
Go
59 lines
1.4 KiB
Go
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)
|
|
}
|