1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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")
}
|