forked from IBM/guestbook
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
293 lines (247 loc) · 7.41 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"encoding/json"
"math/rand"
"net/http"
"os"
"strings"
"time"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
"github.com/xyproto/simpleredis"
)
var (
// For when Redis is used
masterPool *simpleredis.ConnectionPool
slavePool *simpleredis.ConnectionPool
// For when Redis is not used, we just keep it in memory
lists map[string][]string = map[string][]string{}
// For Healthz
startTime time.Time
delay float64 = 10 + 5*rand.Float64()
)
type Input struct {
InputText string `json:"input_text"`
}
type Tone struct {
ToneName string `json:"tone_name"`
}
func GetList(key string) ([]string, error) {
// Using Redis
if slavePool != nil {
list := simpleredis.NewList(slavePool, key)
if result, err := list.GetAll(); err == nil {
return result, err
}
// if we can't talk to the slave then assume its not running yet
// so just try to use the master instead
}
// if the slave doesn't exist, read from the master
if masterPool != nil {
list := simpleredis.NewList(masterPool, key)
return list.GetAll()
}
// if neither exist, we're probably in "in-memory" mode
return lists[key], nil
}
func AppendToList(item string, key string) ([]string, error) {
var err error
items := []string{}
// Using Redis
if masterPool != nil {
list := simpleredis.NewList(masterPool, key)
list.Add(item)
items, err = list.GetAll()
if err != nil {
return nil, err
}
} else {
items = lists[key]
items = append(items, item)
lists[key] = items
}
return items, nil
}
func ListRangeHandler(rw http.ResponseWriter, req *http.Request) {
var data []byte
items, err := GetList(mux.Vars(req)["key"])
if err != nil {
data = []byte("Error getting list: " + err.Error() + "\n")
} else {
if data, err = json.MarshalIndent(items, "", ""); err != nil {
data = []byte("Error marhsalling list: " + err.Error() + "\n")
}
}
rw.Write(data)
}
func ListPushHandler(rw http.ResponseWriter, req *http.Request) {
var data []byte
key := mux.Vars(req)["key"]
value := mux.Vars(req)["value"]
// propogate headers to analyzer service
headers := getForwardHeaders(req.Header)
// Add in the "tone" analyzer results
value += " : " + getPrimaryTone(value, headers)
items, err := AppendToList(value, key)
if err != nil {
data = []byte("Error adding to list: " + err.Error() + "\n")
} else {
if data, err = json.MarshalIndent(items, "", ""); err != nil {
data = []byte("Error marshalling list: " + err.Error() + "\n")
}
}
rw.Write(data)
}
func InfoHandler(rw http.ResponseWriter, req *http.Request) {
info := ""
// Using Redis
if masterPool != nil {
i, err := masterPool.Get(0).Do("INFO")
if err != nil {
info = "Error getting DB info: " + err.Error()
} else {
info = string(i.([]byte))
}
} else {
info = "In-memory datastore (not redis)"
}
rw.Write([]byte(info + "\n"))
}
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
}
data, err := json.MarshalIndent(environment, "", "")
if err != nil {
data = []byte("Error marshalling env vars: " + err.Error())
}
rw.Write(data)
}
func HelloHandler(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte("Hello from guestbook. " +
"Your app is up! (Hostname: " +
os.Getenv("HOSTNAME") +
")\n"))
}
func HealthzHandler(rw http.ResponseWriter, req *http.Request) {
if time.Now().Sub(startTime).Seconds() > delay {
http.Error(rw, "Timeout, Health check error!", http.StatusForbidden)
} else {
rw.Write([]byte("OK!"))
}
}
// Note: This function will not work until we hook-up the Tone Analyzer service
func getPrimaryTone(value string, headers http.Header) (tone string) {
u := Input{InputText: value}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(u)
client := &http.Client{}
req, err := http.NewRequest("POST", "http://analyzer:80/tone", b)
if err != nil {
return "Error talking to tone analyzer service: " + err.Error()
}
req.Header.Add("Content-Type", "application/json")
// add headers
for k := range headers {
req.Header.Add(k, headers.Get(k))
}
// print out headers for debug
// fmt.Printf("getPrimaryTone headers %v", req.Header)
res, err := client.Do(req)
if err != nil {
return "Error detecting tone: " + err.Error()
}
defer res.Body.Close()
body := []Tone{}
json.NewDecoder(res.Body).Decode(&body)
if len(body) > 0 {
// 7 tones: anger, fear, joy, sadness, analytical, confident, and tentative
if body[0].ToneName == "Joy" {
return body[0].ToneName + " (✿◠‿◠)"
} else if body[0].ToneName == "Anger" {
return body[0].ToneName + " (ಠ_ಠ)"
} else if body[0].ToneName == "Fear" {
return body[0].ToneName + " (ง’̀-‘́)ง"
} else if body[0].ToneName == "Sadness" {
return body[0].ToneName + " (︶︿︶)"
} else if body[0].ToneName == "Analytical" {
return body[0].ToneName + " ( °□° )"
} else if body[0].ToneName == "Confident" {
return body[0].ToneName + " (▀̿Ĺ̯▀̿ ̿)"
} else if body[0].ToneName == "Tentative" {
return body[0].ToneName + " (•_•)"
}
return body[0].ToneName
}
return "No Tone Detected"
}
// return the needed header for distributed tracing
func getForwardHeaders(h http.Header) (headers http.Header) {
incomingHeaders := []string{
"x-request-id",
"x-b3-traceid",
"x-b3-spanid",
"x-b3-parentspanid",
"x-b3-sampled",
"x-b3-flags",
"x-ot-span-context"}
header := make(http.Header, len(incomingHeaders))
for _, element := range incomingHeaders {
val := h.Get(element)
if val != "" {
header.Set(element, val)
}
}
return header
}
// Support multiple URL schemes for different use cases
func findRedisURL() string {
host := os.Getenv("REDIS_MASTER_SERVICE_HOST")
port := os.Getenv("REDIS_MASTER_SERVICE_PORT")
password := os.Getenv("REDIS_MASTER_SERVICE_PASSWORD")
master_port := os.Getenv("REDIS_MASTER_PORT")
if host != "" && port != "" && password != "" {
return password + "@" + host + ":" + port
} else if master_port != "" {
return "redis-master:6379"
}
return ""
}
func main() {
// When using Redis, setup our DB connections
url := findRedisURL()
if url != "" {
masterPool = simpleredis.NewConnectionPoolHost(url)
defer masterPool.Close()
slavePool = simpleredis.NewConnectionPoolHost("redis-slave:6379")
defer slavePool.Close()
}
startTime = time.Now()
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)
r.Path("/hello").Methods("GET").HandlerFunc(HelloHandler)
r.Path("/healthz").Methods("GET").HandlerFunc(HealthzHandler)
n := negroni.Classic()
n.UseHandler(r)
n.Run(":3000")
}