Go で Redis を使う

Go で Redis を使うテスト。

ルーティング

GET /get?key=KEYWORD
文字列型から指定した KEYWORD に対応する値をJSON型で表示する
POST /set
文字列値 value をキー KEY にセットする

コード

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
package main

import (
"net/http"
"github.com/labstack/echo"
"github.com/go-redis/redis"
)

type (
redisData struct {
Key string `json:"key"`
Value string `json:"value"`
}
)

func main() {
e := echo.New()

e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World")
})

client := redis.NewClient(&redis.Options{
Addr: "redis:6379",
Password: "",
DB: 0,
})

/**
* Get data by key
*/
e.GET("/get", func(c echo.Context) error {
key := c.QueryParam("key")
val, err := client.Get(key).Result()

if err != nil {
return err
}

data := new(redisData)
data.Key = key
data.Value = value

return c.JSON(http.StatusOK, data)
})

/**
* Create Data
*/
e.POST("/set", func(c echo.Context) error {
key := c.FormValue("key")
value := c.FormValue("value")
err := client.Set(key, value, 0).Err()

if err != nil {
return err
}

data := new(redisData)
data.Key = key
data.Value = value

return c.JSON(http.StatusOK, data)
})

e.Logger.Fatal(e.Start(":8080"))
}