forked from SpectoLabs/hoverfly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin.go
213 lines (169 loc) · 5.13 KB
/
admin.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/negroni"
"github.com/go-zoo/bone"
"github.com/meatballhat/negroni-logrus"
)
// jsonResponse struct encapsulates payload data
type recordedRequests struct {
Data []Payload `json:"data"`
}
type StateRequest struct {
Mode string `json:"mode"`
Destination string `json:"destination"`
}
type messageResponse struct {
Message string `json:"message"`
}
func (d *DBClient) startAdminInterface() {
// starting admin interface
mux := getBoneRouter(*d)
n := negroni.Classic()
n.Use(negronilogrus.NewMiddleware())
n.UseHandler(mux)
// admin interface starting message
log.WithFields(log.Fields{
"RedisAddress": AppConfig.redisAddress,
"AdminPort": AppConfig.adminInterface,
}).Info("Admin interface is starting...")
n.Run(AppConfig.adminInterface)
}
// getBoneRouter returns mux for admin interface
func getBoneRouter(d DBClient) *bone.Mux {
mux := bone.New()
mux.Get("/records", http.HandlerFunc(d.AllRecordsHandler))
mux.Delete("/records", http.HandlerFunc(d.DeleteAllRecordsHandler))
mux.Post("/records", http.HandlerFunc(d.ImportRecordsHandler))
mux.Get("/state", http.HandlerFunc(d.CurrentStateHandler))
mux.Post("/state", http.HandlerFunc(d.stateHandler))
mux.Handle("/*", http.FileServer(http.Dir("static")))
return mux
}
// AllRecordsHandler returns JSON content type http response
func (d *DBClient) AllRecordsHandler(w http.ResponseWriter, req *http.Request) {
records, err := d.getAllRecords()
if err == nil {
w.Header().Set("Content-Type", "application/json")
var response recordedRequests
response.Data = records
b, err := json.Marshal(response)
if err != nil {
log.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
w.Write(b)
return
}
} else {
log.WithFields(log.Fields{
"Error": err.Error(),
"PasswordUsed": AppConfig.redisPassword,
}).Error("Failed to get data from cache!")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(500) // can't process this entity
return
}
}
func (d *DBClient) ImportRecordsHandler(w http.ResponseWriter, req *http.Request) {
var requests recordedRequests
defer req.Body.Close()
body, err := ioutil.ReadAll(req.Body)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var response messageResponse
if err != nil {
// failed to read response body
log.WithFields(log.Fields{
"error": err.Error(),
}).Error("Could not read response body!")
response.Message = "Bad request. Nothing to import!"
http.Error(w, "Failed to read request body.", 400)
return
}
err = json.Unmarshal(body, &requests)
if err != nil {
w.WriteHeader(422) // can't process this entity
return
}
payloads := requests.Data
if len(payloads) > 0 {
for _, pl := range payloads {
bts, err := json.Marshal(pl)
if err != nil {
log.WithFields(log.Fields{
"error": err.Error(),
}).Error("Failed to marshal json")
} else {
// recalculating request hash and storing it in database
r := request{details: pl.Request}
d.cache.set(r.hash(), bts)
}
}
response.Message = fmt.Sprintf("%d requests imported successfully", len(payloads))
} else {
response.Message = "Bad request. Nothing to import!"
w.WriteHeader(400)
}
b, err := json.Marshal(response)
w.Write(b)
}
func (d *DBClient) DeleteAllRecordsHandler(w http.ResponseWriter, req *http.Request) {
err := d.deleteAllRecords()
w.Header().Set("Content-Type", "application/json")
var response messageResponse
if err != nil {
response.Message = fmt.Sprintf("Something went wrong: %s", err.Error())
w.WriteHeader(500)
} else {
response.Message = "Proxy cache deleted successfuly"
w.WriteHeader(200)
}
b, err := json.Marshal(response)
w.Write(b)
return
}
// CurrentStateHandler returns current state
func (d *DBClient) CurrentStateHandler(w http.ResponseWriter, req *http.Request) {
var resp StateRequest
resp.Mode = AppConfig.mode
resp.Destination = AppConfig.destination
b, _ := json.Marshal(resp)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Write(b)
}
// stateHandler handles current proxy state
func (d *DBClient) stateHandler(w http.ResponseWriter, r *http.Request) {
var stateRequest StateRequest
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
// failed to read response body
log.WithFields(log.Fields{
"error": err.Error(),
}).Error("Could not read response body!")
http.Error(w, "Failed to read request body.", 400)
return
}
err = json.Unmarshal(body, &stateRequest)
if err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // can't process this entity
return
}
log.WithFields(log.Fields{
"newState": stateRequest.Mode,
"body": string(body),
}).Info("Handling state change request!")
// setting new state
AppConfig.mode = stateRequest.Mode
var resp StateRequest
resp.Mode = stateRequest.Mode
resp.Destination = AppConfig.destination
b, _ := json.Marshal(resp)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Write(b)
}