-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
100 lines (86 loc) · 2.57 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
package main
import (
"encoding/json"
"flag"
"net/http"
"os"
"strings"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
"github.com/xyproto/simpleredis/v2"
)
var (
redisEnabled bool
masterPool *simpleredis.ConnectionPool
replicaPool *simpleredis.ConnectionPool
// in-memory guestbook
guestbookEntries = make([]string, 0)
)
func ListRangeHandler(rw http.ResponseWriter, req *http.Request) {
key := mux.Vars(req)["key"]
var membersJSON []byte
if redisEnabled {
list := simpleredis.NewList(replicaPool, key)
members := HandleError(list.GetAll()).([]string)
membersJSON = HandleError(json.MarshalIndent(members, "", " ")).([]byte)
} else {
membersJSON = HandleError(json.MarshalIndent(guestbookEntries, "", " ")).([]byte)
}
rw.Write(membersJSON)
}
func ListPushHandler(rw http.ResponseWriter, req *http.Request) {
key := mux.Vars(req)["key"]
value := mux.Vars(req)["value"]
if redisEnabled {
list := simpleredis.NewList(masterPool, key)
HandleError(nil, list.Add(value))
} else {
guestbookEntries = append(guestbookEntries, value)
}
ListRangeHandler(rw, req)
}
func InfoHandler(rw http.ResponseWriter, req *http.Request) {
var info []byte
if redisEnabled {
info = HandleError(masterPool.Get(0).Do("INFO")).([]byte)
} else {
info = []byte(`redis not enabled`)
}
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() {
redisMaster := flag.String("redis-master", "", "Redis master (e.g. redis-master:6379)")
redisReplica := flag.String("redis-replica", "", "Redis replica (e.g. redis-replica:6379)")
redisEnabled = *redisMaster != "" && *redisReplica != ""
if redisEnabled {
masterPool = simpleredis.NewConnectionPoolHost(*redisMaster)
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")
}