56 lines
1.3 KiB
Go
56 lines
1.3 KiB
Go
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"
|
|
|
|
log := log.With(
|
|
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))
|
|
render.JSON(w, r, resp.Error("cannot get file"))
|
|
}
|
|
}
|
|
}
|
|
|
|
func renderObject(w http.ResponseWriter, r *http.Request, obj io.Reader) error {
|
|
_, err := io.Copy(w, obj)
|
|
return err
|
|
}
|