-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
197 lines (161 loc) · 4.82 KB
/
handler.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
package main
import (
"compress/gzip"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"time"
"github.com/rs/zerolog/log"
)
// HandlerAddExpectation handler parses request and adds expectation to global expectations list
func HandlerAddExpectation(w http.ResponseWriter, r *http.Request) {
fLog := log.With().Str("function", "HandlerAddExpectation").Logger()
if r.Method != "POST" {
fLog.Panic().Msgf("Wrong method %s", r.Method)
return
}
exp := ExpectationFromReadCloser(r.Body)
var exps = ControllerAddExpectation(exp.Key, exp, nil)
expsjson, err := json.Marshal(exps)
if err != nil {
fLog.Panic().Err(err)
return
}
w.Write(expsjson)
}
// HandlerRemoveExpectation handler parses request and deletes expectation from global expectations list
func HandlerRemoveExpectation(w http.ResponseWriter, r *http.Request) {
fLog := log.With().Str("function", "HandlerRemoveExpectation").Logger()
if r.Method != "POST" {
fLog.Panic().Msgf("Wrong method %s", r.Method)
return
}
defer r.Body.Close()
requestBody := ExpectationRemove{}
bodyDecoder := json.NewDecoder(r.Body)
err := bodyDecoder.Decode(&requestBody)
if err != nil {
fLog.Panic().Err(err)
return
}
var exps = ControllerRemoveExpectation(requestBody.Key, nil)
expsjson, err := json.Marshal(exps)
if err != nil {
fLog.Panic().Err(err)
return
}
w.Write(expsjson)
}
// HandlerGetExpectations handler parses request and returns global expectations list
func HandlerGetExpectations(w http.ResponseWriter, r *http.Request) {
fLog := log.With().Str("function", "HandlerGetExpectations").Logger()
if r.Method != "GET" {
fLog.Panic().Msgf("Wrong method %s", r.Method)
return
}
var exps = ControllerGetExpectations(nil)
expsjson, err := json.Marshal(exps)
if err != nil {
fLog.Panic().Err(err)
return
}
fmt.Fprint(w, string(expsjson))
}
// HandlerStatus handler returns applications status
func HandlerStatus(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "gozzmock status is OK")
}
// HandlerDefault handler is an entry point for all incoming requests
func HandlerDefault(w http.ResponseWriter, r *http.Request) {
generateResponseToResponseWriter(w, ControllerTranslateRequestToExpectation(r))
}
func uploadResponseToResponseWriter(w http.ResponseWriter, resp *ExpectationResponse) {
w.WriteHeader(resp.HTTPCode)
w.Write([]byte(resp.Body))
if resp.Headers != nil {
for name, value := range *resp.Headers {
w.Header().Set(name, value)
}
}
}
func generateResponseToResponseWriter(w http.ResponseWriter, req *ExpectationRequest) {
fLog := log.With().Str("function", "generateResponseToResponseWriter").Logger()
storedExpectations := ControllerGetExpectations(nil)
orderedStoredExpectations := ControllerSortExpectationsByPriority(storedExpectations)
for i := 0; i < len(orderedStoredExpectations); i++ {
exp := orderedStoredExpectations[i]
if !ControllerRequestPassesFilter(req, exp.Request) {
continue
}
time.Sleep(time.Second * exp.Delay)
if exp.Response != nil {
fLog.Info().Str("key", exp.Key).Msg("Apply response expectation")
uploadResponseToResponseWriter(w, exp.Response)
return
}
if exp.Forward != nil {
fLog.Info().Str("key", exp.Key).Msg("Apply forward expectation")
httpReq := ControllerCreateHTTPRequest(req, exp.Forward)
doHTTPRequest(w, httpReq)
return
}
}
fLog.Error().Msg("No expectations in gozzmock for request!")
w.WriteHeader(http.StatusNotImplemented)
w.Write([]byte("No expectations in gozzmock for request!"))
}
func readResponseBody(resp *http.Response) ([]byte, error) {
var reader io.ReadCloser
if resp.Header.Get("Content-Encoding") == "gzip" {
reader, err := gzip.NewReader(resp.Body)
defer reader.Close()
if err != nil {
return nil, err
}
} else {
reader = resp.Body
}
body, err := ioutil.ReadAll(reader)
if err != nil {
return nil, err
}
return body, nil
}
// LogRequest dumps http request and writes content to log
func LogRequest(req *http.Request) {
fLog := log.With().Str("function", "LogRequest").Logger()
reqDumped, err := httputil.DumpRequest(req, true)
if err != nil {
fLog.Panic().Err(err)
return
}
fLog.Debug().Str("messagetype", "Request").Msg(string(reqDumped))
}
func doHTTPRequest(w http.ResponseWriter, httpReq *http.Request) {
fLog := log.With().Str("function", "doHTTPRequest").Logger()
if httpReq == nil {
fLog.Panic().Msg("http.Request is nil")
return
}
httpClient := &http.Client{}
resp, err := httpClient.Do(httpReq)
if err != nil {
fLog.Panic().Err(err)
return
}
body, err := readResponseBody(resp)
if err != nil {
fLog.Panic().Err(err)
return
}
fLog.Debug().Str("messagetype", "ResponseBody").Msg(string(body))
w.WriteHeader(resp.StatusCode)
w.Write(body)
headers := *ControllerTranslateHTTPHeadersToExpHeaders(resp.Header)
for name, value := range headers {
w.Header().Set(name, value)
}
}