From a30c96160333edb002e5b1cc18ef20b07ddc78ee Mon Sep 17 00:00:00 2001 From: "Pablo M. Bermudo Garay" Date: Mon, 7 Feb 2022 22:43:32 +0100 Subject: Initial commit Basic in-memory object store. --- main.go | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 main.go (limited to 'main.go') diff --git a/main.go b/main.go new file mode 100644 index 0000000..268c689 --- /dev/null +++ b/main.go @@ -0,0 +1,83 @@ +// Storehouse: HTTP object store server +// +// Licensed under CC0 1.0 Universal: +// https://creativecommons.org/publicdomain/zero/1.0/legalcode +package main + +import ( + "io/ioutil" + "log" + "net/http" + + "github.com/labstack/echo/v4" + "github.com/pablombg/storehouse/objectstore" +) + +type storehouse struct { + objects *objectstore.MemObjectStore +} + +func InitStorehouse() *storehouse { + objects := objectstore.NewMemBackend() + return &storehouse{objects: objects} +} + +func (s *storehouse) putObject(c echo.Context) error { + bucketId := c.Param("bucketId") + objectId := c.Param("objectId") + + 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) + + s.objects.CreateObject(bucketId, objectId, content) + m := &objectIdJSON{Id: objectId} + return c.JSON(http.StatusCreated, m) +} + +func (s *storehouse) getObject(c echo.Context) error { + bucketId := c.Param("bucketId") + objectId := c.Param("objectId") + + object, err := s.objects.GetObject(bucketId, objectId) + if err != nil { + log.Println(err) + m := &errorJSON{Error: "Object not found"} + return c.JSON(http.StatusNotFound, m) + } + + return c.String(http.StatusOK, object) +} + +func (s *storehouse) deleteObject(c echo.Context) error { + bucketId := c.Param("bucketId") + objectId := c.Param("objectId") + + err := s.objects.DeleteObject(bucketId, objectId) + if err != nil { + log.Println(err) + m := &errorJSON{Error: "Object not found"} + return c.JSON(http.StatusNotFound, m) + } + + m := &infoJSON{Info: "Object deleted"} + return c.JSON(http.StatusOK, m) +} + +func main() { + // Initialization + s := InitStorehouse() + e := echo.New() + + // Routes + e.GET("/objects/:bucketId/:objectId", s.getObject) + e.PUT("/objects/:bucketId/:objectId", s.putObject) + e.DELETE("/objects/:bucketId/:objectId", s.deleteObject) + + // Start server + e.Start(":8080") +} -- cgit v1.2.3-70-g09d2