-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
114 lines (92 loc) · 1.93 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
102
103
104
105
106
107
108
109
110
111
112
113
114
package main
import (
"encoding/json"
"flag"
"log"
"net/http"
"time"
"github.com/rueian/rueidis"
)
type Value struct {
Value string `json:"value"`
Took string `json:"took"`
}
func resp(w http.ResponseWriter, status int, body any) {
w.WriteHeader(status)
err := json.NewEncoder(w).Encode(body)
if err != nil {
log.Println(err)
}
}
func main() {
port := flag.String("port", "3000", "http port server")
flag.Parse()
if port == nil {
log.Println("need to specify port")
return
}
c, err := rueidis.NewClient(rueidis.ClientOption{
InitAddress: []string{"127.0.0.1:6379"},
})
if err != nil {
panic(err)
}
defer c.Close()
http.HandleFunc("/get", func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
command := c.B().
Get().Key("key").Build()
res := c.Do(r.Context(), command)
if res.Error() != nil {
resp(w, 500, err)
return
}
value, err := res.ToString()
if res.Error() != nil {
resp(w, 500, err)
return
}
resp(w, 200, Value{
Value: value,
Took: time.Since(start).String(),
})
})
http.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
value := time.Now().Format(time.DateTime)
command := c.B().
Set().
Key("key").
Value(value).
Build()
err = c.Do(r.Context(), command).Error()
if err != nil {
resp(w, 500, err)
return
}
resp(w, 200, Value{
Value: value,
Took: time.Since(start).String(),
})
})
http.HandleFunc("/get-cached", func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
command := c.B().
Get().Key("key").Cache()
res := c.DoCache(r.Context(), command, time.Second*60)
if res.Error() != nil {
resp(w, 500, err)
return
}
value, err := res.ToString()
if res.Error() != nil {
resp(w, 500, err)
return
}
resp(w, 200, Value{
Value: value,
Took: time.Since(start).String(),
})
})
log.Fatal(http.ListenAndServe(":"+*port, nil))
}