get recipe image http handler

This commit is contained in:
yash 2024-01-23 14:40:45 +03:00
parent 55c7c2bff6
commit 94ff1e9872
2 changed files with 55 additions and 1 deletions

View File

@ -0,0 +1,54 @@
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))
}
}
}
func renderObject(w http.ResponseWriter, r *http.Request, obj io.Reader) error {
_, err := io.Copy(w, obj)
return err
}

View File

@ -99,7 +99,7 @@ func (o *ObjStorage) SaveRecipeImage(ctx context.Context, imageFile io.Reader, f
} }
// RecipeImage gets image from recipe's images bucket by filename. // RecipeImage gets image from recipe's images bucket by filename.
func (o *ObjStorage) RecipeImage(ctx context.Context, filename string) (*minio.Object, error) { func (o *ObjStorage) RecipeImage(ctx context.Context, filename string) (io.ReadCloser, error) {
const op = "media_storage.minio.RecipeImage" const op = "media_storage.minio.RecipeImage"
err := o.checkBucketExists(ctx, recipeImgBucket) err := o.checkBucketExists(ctx, recipeImgBucket)
if err != nil { if err != nil {