-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
101 lines (85 loc) · 2.13 KB
/
main.go
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"encoding/json"
"github.com/gin-gonic/gin"
"io/ioutil"
"log"
"net/http"
"os"
"s3db/internal"
)
type App struct {
s3Config internal.S3Config
}
func main() {
app := NewApp()
r := gin.Default()
r.GET("/records/:id", app.handleGetRecord)
r.POST("/records/:id", app.handlePostRecord)
r.GET("/records", app.handleGetRecords)
r.POST("/drop-db", app.handleDropDB)
err := r.Run()
if err != nil {
log.Fatal(err)
}
}
func NewApp() *App {
return &App{
s3Config: internal.S3Config{
Region: os.Getenv("S3_REGION"),
AccessKeyID: os.Getenv("S3_ACCESS_KEY_ID"),
SecretAccessKey: os.Getenv("S3_SECRET_ACCESS_KEY"),
BucketName: os.Getenv("S3_BUCKET_NAME"),
},
}
}
func (app *App) handleGetRecord(c *gin.Context) {
key := c.Param("id")
resp, err := internal.GetRecord(app.s3Config, key)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
var jsonData interface{}
err = json.Unmarshal([]byte(resp), &jsonData)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, jsonData)
}
func (app *App) handlePostRecord(c *gin.Context) {
key := c.Param("id")
serializedBody, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
log.Fatal(err)
}
var jsonData interface{}
err = json.Unmarshal(serializedBody, &jsonData)
if err != nil {
c.String(http.StatusBadRequest, "got a non-JSON body")
return
}
err = internal.NewRecord(app.s3Config, key, string(serializedBody))
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
return
}
c.Status(http.StatusCreated)
}
func (app *App) handleGetRecords(c *gin.Context) {
allObjectsList, err := internal.ListAllObjects(app.s3Config)
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
return
}
c.JSON(http.StatusOK, allObjectsList)
}
func (app *App) handleDropDB(c *gin.Context) {
err := internal.DropDB(app.s3Config)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Database dropped successfully"})
}