recipes2/internal/http-server/handlers/recipeImage/recipeImage.go

56 lines
1.3 KiB
Go
Raw Normal View History

2024-01-23 13:40:45 +02:00
package recipeimage
import (
"context"
"io"
"log/slog"
"net/http"
resp "recipes/internal/lib/api/response"
"recipes/internal/lib/logger/sl"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
)
type ImageProvider interface {
RecipeImage(ctx context.Context, filename string) (io.ReadCloser, error)
}
func New(log *slog.Logger, imageProvider ImageProvider) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
const op = "http-server.handlers.recipeImage.New"
2024-01-27 20:42:23 +02:00
log := log.With(
2024-01-23 13:40:45 +02:00
slog.String("op", op),
slog.String("request_id", middleware.GetReqID(r.Context())),
)
// get filename
filename := r.URL.Query().Get("filename")
if filename == "" {
log.Error("filename not in query")
render.JSON(w, r, resp.Error("invalid request"))
return
}
// get object
obj, err := imageProvider.RecipeImage(r.Context(), filename)
if err != nil {
log.Error("cannot get file", sl.Err(err))
render.JSON(w, r, resp.Error("cannot get file"))
return
}
defer obj.Close()
// return object
err = renderObject(w, r, obj)
if err != nil {
log.Error("Fail on rendering object", sl.Err(err))
2024-01-25 14:44:38 +02:00
render.JSON(w, r, resp.Error("cannot get file"))
2024-01-23 13:40:45 +02:00
}
}
}
func renderObject(w http.ResponseWriter, r *http.Request, obj io.Reader) error {
_, err := io.Copy(w, obj)
return err
}