Files
meilisearch-showcase/internal/interfaces/http/router.go
T

115 lines
3.1 KiB
Go

// Package http is a driving adapter: it turns HTTP requests into use-case
// calls and domain results into JSON. No business logic here.
package http
import (
"encoding/json"
"errors"
"log/slog"
"net/http"
"strconv"
"git.jokresner.de/johannes/meilisearch-showcase/internal/app"
"git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
)
type Handler struct {
svc *app.CatalogService
log *slog.Logger
}
func NewHandler(svc *app.CatalogService, log *slog.Logger) *Handler {
return &Handler{svc: svc, log: log}
}
func (h *Handler) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) })
mux.HandleFunc("GET /search", h.search)
mux.HandleFunc("GET /movies/{id}", h.get)
mux.HandleFunc("POST /movies", h.importMovies)
mux.HandleFunc("DELETE /movies/{id}", h.delete)
return mux
}
func (h *Handler) search(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
query := catalog.Query{
Text: q.Get("q"),
Genre: q.Get("genre"),
MinYear: atoi(q.Get("min_year")),
MaxYear: atoi(q.Get("max_year")),
MinRating: atof(q.Get("min_rating")),
Limit: atoi(q.Get("limit")),
Offset: atoi(q.Get("offset")),
}
res, err := h.svc.Search(r.Context(), query)
if err != nil {
h.fail(w, err)
return
}
writeJSON(w, http.StatusOK, toSearchResponse(res))
}
func (h *Handler) get(w http.ResponseWriter, r *http.Request) {
m, err := h.svc.Get(r.Context(), r.PathValue("id"))
if err != nil {
h.fail(w, err)
return
}
writeJSON(w, http.StatusOK, toMovieResponse(m))
}
func (h *Handler) importMovies(w http.ResponseWriter, r *http.Request) {
var in []app.MovieInput
// Bound the body: this is a trust boundary.
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8<<20)).Decode(&in); err != nil {
writeJSON(w, http.StatusBadRequest, errorResponse{Error: "invalid json body"})
return
}
n, err := h.svc.ImportMovies(r.Context(), in)
if err != nil {
h.fail(w, err)
return
}
writeJSON(w, http.StatusAccepted, map[string]int{"indexed": n})
}
func (h *Handler) delete(w http.ResponseWriter, r *http.Request) {
if err := h.svc.Delete(r.Context(), r.PathValue("id")); err != nil {
h.fail(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// fail maps domain errors to status codes; everything unknown is a 500 and is
// logged instead of being echoed to the client.
func (h *Handler) fail(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, catalog.ErrNotFound):
writeJSON(w, http.StatusNotFound, errorResponse{Error: "not found"})
case errors.Is(err, catalog.ErrInvalidMovie):
writeJSON(w, http.StatusBadRequest, errorResponse{Error: err.Error()})
default:
h.log.Error("request failed", "err", err)
writeJSON(w, http.StatusInternalServerError, errorResponse{Error: "internal error"})
}
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func atoi(s string) int {
n, _ := strconv.Atoi(s)
return n
}
func atof(s string) float64 {
f, _ := strconv.ParseFloat(s, 64)
return f
}