-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
212 lines (192 loc) · 4.58 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
211
212
package main
import (
"encoding/json"
"fmt"
"gopkg.in/mgo.v2/bson"
"html/template"
"io/ioutil"
"net/http"
"net/http/httputil"
"regexp"
"strings"
"time"
)
// Handler for root resource, returns web page
func rootHandler(w http.ResponseWriter, req *http.Request) {
var rootTemplate, err = template.ParseFiles(indexHtml)
check(err)
rootTemplate.Execute(w, nil)
}
// Handler for Messages resource. Verfies received data and sends email
func messageHandler(w http.ResponseWriter, req *http.Request) {
// Parse Data
if req.Method == "POST" {
values := req.URL.Query()
password := values.Get("password")
if password != Password {
w.WriteHeader(403)
return
}
// Build Message
bytes, err := ioutil.ReadAll(req.Body)
check(err)
var email Message
err = json.Unmarshal(bytes, &email)
if err != nil {
http.Error(w, "Invalid JSON", 400)
return
}
// Validate Fields
for _, to := range email.To {
matchTo, _ := regexp.MatchString(emailRegex, to)
if !matchTo {
if Debug {
ErrorLog.Println("To address not valid email: " + to)
}
http.Error(w, "Invalid 'To' Email Address.", 400)
return
}
}
matchFrom, _ := regexp.MatchString(emailRegex, email.From)
if !matchFrom {
if Debug {
ErrorLog.Println("From address not valid email.")
}
http.Error(w, "Invalid 'From' Email Address.", 400)
return
}
sender := chooseMailSender()
if sender == nil {
http.Error(w, "No Mail Server Available.", 500)
return
}
if !requestSlot() {
http.Error(w, "Over throttle limit.", 403)
return
}
status := sender.Send(email)
w.WriteHeader(status)
return
}
// Other methods not supported
w.WriteHeader(405)
}
// Handler to return status of MailServers
func statusHandler(w http.ResponseWriter, req *http.Request) {
result := make(map[string]bool)
for s, b := range Servers {
result[s.GetName()] = b
}
statusJson, err := json.Marshal(result)
check(err)
fmt.Fprintf(w, string(statusJson))
}
func contactsHandler(w http.ResponseWriter, req *http.Request) {
values := req.URL.Query()
id := values.Get("id")
tag := values.Get("tag")
name := values.Get("name")
path := req.URL.Path
pieces := strings.Split(path, "/")
// If ID is in Path it takes precedence
if len(pieces) > 2 && len(pieces[2]) > 0 {
id = pieces[2]
}
if len(id) > 0 {
if !bson.IsObjectIdHex(id) {
w.WriteHeader(404)
return
}
}
switch req.Method {
case "GET":
if Debug {
InfoLog.Println("Get Contact")
}
var contacts []Contact
if len(id) > 0 {
contacts = datastore.RetrieveContactsBy("id", id)
} else if len(tag) > 0 {
contacts = datastore.RetrieveContactsBy("tag", tag)
} else if len(name) > 0 {
contacts = datastore.RetrieveContactsBy("name", name)
} else {
// Fetch All
}
jsonContacts, err := json.Marshal(contacts)
if err != nil {
ErrorLog.Println("Error marshalling Contacts.")
w.WriteHeader(400)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "%s", jsonContacts)
case "POST":
if Debug {
InfoLog.Println("Create Contact")
}
bytes, err := ioutil.ReadAll(req.Body)
check(err)
var contact Contact
err = json.Unmarshal(bytes, &contact)
if err != nil {
http.Error(w, "Invalid JSON", 400)
return
}
result := datastore.StoreContact(contact)
jsonContact, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "%s", jsonContact)
case "PUT":
if Debug {
InfoLog.Println("Update Contact")
}
bytes, err := ioutil.ReadAll(req.Body)
check(err)
var contact Contact
err = json.Unmarshal(bytes, &contact)
if err != nil {
http.Error(w, "Invalid JSON", 400)
return
}
result := datastore.UpdateContact(contact)
jsonContact, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "%s", jsonContact)
case "DELETE":
if Debug {
InfoLog.Println("Delete Contact")
}
if datastore.DeleteContact(id) {
w.WriteHeader(200)
} else {
if Debug {
InfoLog.Println("Could not delete contact: " + id)
}
w.WriteHeader(404)
}
default:
w.WriteHeader(405)
}
}
// Error Handler Wrapper
func errorHandler(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
if Debug {
InfoLog.Println(time.Now().String())
reqDump, _ := httputil.DumpRequest(req, true)
InfoLog.Printf("Request: %s\n\n", reqDump)
}
defer func() {
if e, ok := recover().(error); ok {
w.WriteHeader(500)
ErrorLog.Print("error: ")
ErrorLog.Println(e)
}
}()
fn(w, req)
}
}