From 3aa4d62526537ec0fe624899a2f05566ea80a198 Mon Sep 17 00:00:00 2001 From: "Pablo M. Bermudo Garay" Date: Wed, 9 Feb 2022 21:37:44 +0100 Subject: Add and use file backend --- main.go | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) (limited to 'main.go') diff --git a/main.go b/main.go index c4104e3..36f51e4 100644 --- a/main.go +++ b/main.go @@ -5,9 +5,11 @@ package main import ( + "errors" "io/ioutil" "log" "net/http" + "os" "github.com/labstack/echo/v4" "github.com/pablombg/storehouse/objectstore" @@ -18,7 +20,8 @@ type storehouse struct { } func InitStorehouse() *storehouse { - objects := objectstore.NewMemBackend() + // objects := objectstore.NewMemBackend() + objects := objectstore.NewFileBackend("data") return &storehouse{objects: objects} } @@ -26,16 +29,15 @@ func (s *storehouse) putObject(c echo.Context) error { bucketId := c.Param("bucketId") objectId := c.Param("objectId") - // Get body as a string + // Get request body bodyBytes, err := ioutil.ReadAll(c.Request().Body) if err != nil { log.Printf("Error reading body: %v", err) m := &errorJSON{Error: "Error reading body"} return c.JSON(http.StatusInternalServerError, m) } - content := string(bodyBytes) - err = s.objects.CreateObject(bucketId, objectId, content) + err = s.objects.CreateObject(bucketId, objectId, bodyBytes) // Check errors creating the object if err != nil { log.Printf("Error creating the object: %v", err) @@ -61,10 +63,15 @@ func (s *storehouse) getObject(c echo.Context) error { objectId := c.Param("objectId") object, err := s.objects.GetObject(bucketId, objectId) - if err != nil { - log.Println(err) - m := &errorJSON{Error: "Object not found"} + if errors.Is(err, os.ErrNotExist) { + msg := "Object not found" + log.Println(msg) + m := &errorJSON{Error: msg} return c.JSON(http.StatusNotFound, m) + } else if err != nil { + log.Println(err) + m := &errorJSON{Error: "Internal error"} + return c.JSON(http.StatusInternalServerError, m) } return c.String(http.StatusOK, object) @@ -75,10 +82,15 @@ func (s *storehouse) deleteObject(c echo.Context) error { objectId := c.Param("objectId") err := s.objects.DeleteObject(bucketId, objectId) - if err != nil { - log.Println(err) - m := &errorJSON{Error: "Object not found"} + if errors.Is(err, os.ErrNotExist) { + msg := "Object not found" + log.Println(msg) + m := &errorJSON{Error: msg} return c.JSON(http.StatusNotFound, m) + } else if err != nil { + log.Println(err) + m := &errorJSON{Error: "Internal error"} + return c.JSON(http.StatusInternalServerError, m) } m := &infoJSON{Info: "Object deleted"} -- cgit v1.2.3-70-g09d2