diff options
| author | Pablo M. Bermudo Garay <pablombg@gmail.com> | 2022-02-09 21:37:44 +0100 |
|---|---|---|
| committer | Pablo M. Bermudo Garay <pablombg@gmail.com> | 2022-02-10 13:14:19 +0100 |
| commit | 3aa4d62526537ec0fe624899a2f05566ea80a198 (patch) | |
| tree | 6ab3bfe1de3f8b598563b0fc71a84cd300ffafa9 /main.go | |
| parent | 53667583c094252818f203b9233a7726d0a4e8a0 (diff) | |
Add and use file backend
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"} |
