diff options
Diffstat (limited to 'main.go')
| -rw-r--r-- | main.go | 32 |
1 files changed, 22 insertions, 10 deletions
@@ -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"} |
