-
Notifications
You must be signed in to change notification settings - Fork 1
/
handlers.go
210 lines (182 loc) · 6.35 KB
/
handlers.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
package main
import (
"errors"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
rj "github.com/bottlenose-inc/rapidjson" // faster json handling
)
// SendErrorResponse sends a response with the provided error message and status code.
func SendErrorResponse(w http.ResponseWriter, message string, status int) {
errorsCounter.Inc()
errorJson := rj.NewDoc()
defer errorJson.Free()
errorCt := errorJson.GetContainerNewObj()
errorCt.AddValue("error", message)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_, err := w.Write(errorJson.Bytes())
if err != nil {
logger.Error("Error writing response: "+err.Error(), map[string]string{"error": errorJson.String()})
}
}
// GetRequests is a generic function that parses properly formatted requests to an augmentation.
// It ensures the correct Content-Type header is provided and ensures the request is properly
// formatted. Requests are also truncated to BODY_LIMIT_BYTES to avoid huge requests causing problems.
func GetRequests(w http.ResponseWriter, r *http.Request) (*rj.Doc, error) {
var emptyMap *rj.Doc
// Send error response if incorrect Content-Type is provided
if r.Header.Get("Content-Type") != "application/json" {
invalidRequestsCounter.Inc()
logger.Warning("Client request did not set Content-Type header to application/json", map[string]string{"Content-Type": r.Header.Get("Content-Type")})
SendErrorResponse(w, "Content-Type must be set to application/json", http.StatusBadRequest)
return emptyMap, errors.New("Content-Type must be set to application/json")
}
// Read body up to size of BODY_LIMIT_BYTES
body, err := ioutil.ReadAll(io.LimitReader(r.Body, BODY_LIMIT_BYTES))
if err != nil {
logger.Error("Error reading request body: " + err.Error())
SendErrorResponse(w, "Error reading request body", http.StatusInternalServerError)
return emptyMap, err
}
if err := r.Body.Close(); err != nil {
logger.Error("Error closing body: " + err.Error())
SendErrorResponse(w, "Error reading request body", http.StatusInternalServerError)
return emptyMap, err
}
// Parse request JSON
requestJson, err := rj.NewParsedJson(body)
if err != nil {
invalidRequestsCounter.Inc()
logger.Warning("Client request was invalid JSON: "+err.Error(), map[string]string{"body": string(body)})
SendErrorResponse(w, "Unable to parse request - invalid JSON detected", http.StatusBadRequest)
requestJson.Free()
return emptyMap, err
}
return requestJson, err
}
// HandlerWrapper is "wrapped" around all handlers to allow generation of
// common metrics we want for every valid api call.
func HandlerWrapper(handler http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
http.HandlerFunc(handler).ServeHTTP(w, r)
totalRequestsCounter.Inc()
requestDurationCounter.Add(time.Since(start).Seconds() / 1000)
})
}
// NotFound sends a 404 response.
func NotFound(w http.ResponseWriter, r *http.Request) {
invalidRequestsCounter.Inc()
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
_, err := w.Write(notFound)
if err != nil {
// Should not run into this error...
logger.Error("Error encoding 404 response: " + err.Error())
}
}
// Usage sends the usage information response.
func Usage(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, err := w.Write(usage)
if err != nil {
// Should not run into this error...
logger.Error("Error encoding usage response: " + err.Error())
}
}
// detect language
func LanguageDetectorHandler(w http.ResponseWriter, r *http.Request) {
requestJson, err := GetRequests(w, r)
if err != nil {
incUnsuccessfulCounter()
return
}
defer requestJson.Free()
requestCt := requestJson.GetContainer()
if requestCt.GetType() == rj.TypeNull {
return
}
requestsCt, err := requestCt.GetMember("request")
if err != nil {
invalidRequestsCounter.Inc()
logger.Warning("Client request was invalid JSON: " + err.Error())
SendErrorResponse(w, "Unable to parse request - invalid JSON detected", http.StatusBadRequest)
return
}
requests, _, err := requestsCt.GetArray()
respCode := http.StatusOK
responses := rj.NewDoc()
defer responses.Free()
responsesCt := responses.GetContainerNewObj()
responsesArray := responses.NewContainerArray()
responsesCt.AddMember("response", responsesArray)
responsesArray, _ = responsesCt.GetMember("response")
for _, request := range requests {
response := responses.NewContainerObj()
text, err := request.GetMember("text")
if err != nil {
incUnsuccessfulCounter()
response.AddValue("error", "Missing text key")
respCode = http.StatusBadRequest
err = responsesArray.ArrayAppendContainer(response)
if err != nil {
SendErrorResponse(w, err.Error(), http.StatusInternalServerError)
return
}
continue
}
textStr, err := text.GetString()
textStr = StripExtras(textStr)
code := Detect_language(textStr)
name, found := KnownLanguages[code]
if !found {
name = "Unknown"
respCode = http.StatusNonAuthoritativeInfo
logger.Warning("Unknown response language code: " + code)
}
response.AddValue("iso6391code", code)
response.AddValue("name", name)
incLanguageCount(name)
// Append newly generated response to responses
err = responsesArray.ArrayAppendContainer(response)
if err != nil {
incUnsuccessfulCounter()
SendErrorResponse(w, err.Error(), http.StatusInternalServerError)
return
}
// Call logProcessed for every object that gets processed
incSuccessfulCounter()
logProcessed()
}
// Send response
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(respCode)
_, err = w.Write(responses.Bytes())
if err != nil {
// Should not run into this error...
logger.Error("Error encoding error response: "+err.Error(), map[string]string{"response": responses.String()})
}
}
func HasPrefix(word string, prefixes []string) bool {
for _, prefix := range prefixes {
if strings.HasPrefix(word, prefix) {
return true
}
}
return false
}
// remove mentions and links from text, as these can skew detection
func StripExtras(text string) string {
var result string
prefixes := []string{"@", "http"}
for _, word := range strings.Fields(text) {
if !HasPrefix(word, prefixes) {
result = result + word + " "
}
}
return result
}