-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
96 lines (78 loc) · 1.97 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
package main
import (
"context"
"os"
"github.com/gofiber/fiber/v2"
"github.com/redis/go-redis/v9"
)
// Struct for KeyValue
type KeyValue struct {
Key string `json:"key"`
Value string `json:"value"`
}
func main() {
// Init fiber - For Server request handling
app := fiber.New()
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
addr = "localhost:6379"
}
rdb := redis.NewClient(&redis.Options{
Addr: addr,
})
_, err := rdb.Ping(context.Background()).Result()
if err != nil {
panic(err)
}
app.Get("/health", func(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusOK)
})
app.Get("/key/:key", func(c *fiber.Ctx) error {
key := c.Params("key")
val, err := rdb.Get(c.Context(), key).Result()
if err != nil {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
"error": "Key not found",
})
}
return c.JSON(KeyValue{Key: key, Value: val})
})
app.Post("/key", func(c *fiber.Ctx) error {
var kv KeyValue
if err := c.BodyParser(&kv); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "Failed to set key-value pair",
})
}
return c.JSON(kv)
})
app.Put("/key:key", func(c *fiber.Ctx) error {
key := c.Params("key")
var kv KeyValue
if err := c.BodyParser(&kv); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "Invalid request body",
})
}
err = rdb.Set(c.Context(), key, kv.Value, 0).Err()
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "Failed to update key-value pair",
})
}
return c.JSON(KeyValue{Key: key, Value: kv.Value})
})
app.Delete("/key/:key", func(c *fiber.Ctx) error {
key := c.Params("key")
err := rdb.Del(c.Context(), key).Err()
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "Failed to delete key-value pair",
})
}
return c.SendStatus(fiber.StatusNoContent)
})
if err := app.Listen(":4000"); err != nil {
panic(err)
}
}