-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
75 lines (63 loc) · 1.92 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
package main
import (
"encoding/json"
"net/http"
"os"
"strings"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
"github.com/xyproto/simpleredis/v2"
)
var (
masterPool *simpleredis.ConnectionPool
replicaPool *simpleredis.ConnectionPool
)
func ListRangeHandler(rw http.ResponseWriter, req *http.Request) {
key := mux.Vars(req)["key"]
list := simpleredis.NewList(replicaPool, key)
members := HandleError(list.GetAll()).([]string)
membersJSON := HandleError(json.MarshalIndent(members, "", " ")).([]byte)
rw.Write(membersJSON)
}
func ListPushHandler(rw http.ResponseWriter, req *http.Request) {
key := mux.Vars(req)["key"]
value := mux.Vars(req)["value"]
list := simpleredis.NewList(masterPool, key)
HandleError(nil, list.Add(value))
ListRangeHandler(rw, req)
}
func InfoHandler(rw http.ResponseWriter, req *http.Request) {
info := HandleError(masterPool.Get(0).Do("INFO")).([]byte)
rw.Write(info)
}
func EnvHandler(rw http.ResponseWriter, req *http.Request) {
environment := make(map[string]string)
for _, item := range os.Environ() {
splits := strings.Split(item, "=")
key := splits[0]
val := strings.Join(splits[1:], "=")
environment[key] = val
}
envJSON := HandleError(json.MarshalIndent(environment, "", " ")).([]byte)
rw.Write(envJSON)
}
func HandleError(result interface{}, err error) (r interface{}) {
if err != nil {
panic(err)
}
return result
}
func main() {
masterPool = simpleredis.NewConnectionPoolHost("redis-master:6379")
defer masterPool.Close()
replicaPool = simpleredis.NewConnectionPoolHost("redis-replica:6379")
defer replicaPool.Close()
r := mux.NewRouter()
r.Path("/lrange/{key}").Methods("GET").HandlerFunc(ListRangeHandler)
r.Path("/rpush/{key}/{value}").Methods("GET").HandlerFunc(ListPushHandler)
r.Path("/info").Methods("GET").HandlerFunc(InfoHandler)
r.Path("/env").Methods("GET").HandlerFunc(EnvHandler)
n := negroni.Classic()
n.UseHandler(r)
n.Run(":3000")
}