-
Notifications
You must be signed in to change notification settings - Fork 204
/
modes.go
205 lines (167 loc) · 6.16 KB
/
modes.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
package modes
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
v2 "github.com/SpectoLabs/hoverfly/core/handlers/v2"
"github.com/SpectoLabs/hoverfly/core/util"
log "github.com/sirupsen/logrus"
"github.com/SpectoLabs/goproxy"
"github.com/SpectoLabs/hoverfly/core/models"
)
// SimulateMode - default mode when Hoverfly looks for captured requests to respond
const Simulate = "simulate"
// SynthesizeMode - all requests are sent to middleware to create response
const Synthesize = "synthesize"
// ModifyMode - middleware is applied to outgoing and incoming traffic
const Modify = "modify"
// CaptureMode - requests are captured and stored in cache
const Capture = "capture"
// SpyMode - simulateMode but will call real service when cache miss
const Spy = "spy"
// DiffMode - calls real service and compares response with simulation
const Diff = "diff"
type Mode interface {
Process(*http.Request, models.RequestDetails) (ProcessResult, error)
SetArguments(arguments ModeArguments)
View() v2.ModeView
}
type ModeArguments struct {
Headers []string
MatchingStrategy *string
Stateful bool
OverwriteDuplicate bool
CaptureOnMiss bool
}
type ProcessResult struct {
Response *http.Response
FixedDelay int
LogNormalDelay *models.ResponseDetailsLogNormal
PostServeActionInputDetails *PostServeActionInputDetails
}
type PostServeActionInputDetails struct {
PostServeAction string
Pair *models.RequestResponsePair
}
func (p ProcessResult) IsResponseDelayable() bool {
return p.FixedDelay > 0 || p.LogNormalDelay != nil
}
func newProcessResult(response *http.Response, fixedDelay int, logNormalDelay *models.ResponseDetailsLogNormal) ProcessResult {
return ProcessResult{Response: response, FixedDelay: fixedDelay, LogNormalDelay: logNormalDelay}
}
func newProcessResultWithPostServeActionInputDetails(response *http.Response, fixedDelay int, logNormalDelay *models.ResponseDetailsLogNormal, postServeActionInputDetails *PostServeActionInputDetails) ProcessResult {
return ProcessResult{Response: response, FixedDelay: fixedDelay, LogNormalDelay: logNormalDelay, PostServeActionInputDetails: postServeActionInputDetails}
}
// ReconstructRequest replaces original request with details provided in Constructor Payload.RequestMatcher
func ReconstructRequest(pair models.RequestResponsePair) (*http.Request, error) {
if pair.Request.Destination == "" {
return nil, fmt.Errorf("failed to reconstruct request, destination not specified")
}
bodyBytes := []byte(pair.Request.Body)
// recompress the request body if the original was encoded
if values, found := pair.Request.Headers["Content-Encoding"]; found {
for _, value := range values {
// Only gzip is supported at the moment
if value == "gzip" {
compressedBody, err := util.CompressGzip(bodyBytes)
if err == nil {
bodyBytes = compressedBody
} else {
// Fail to compress, we should remove the encoding header
delete(pair.Request.Headers, "Content-Encoding")
}
break
}
}
}
newRequest, err := http.NewRequest(
pair.Request.Method,
fmt.Sprintf("%s://%s%s", pair.Request.Scheme, pair.Request.Destination, pair.Request.Path),
bytes.NewBuffer(bodyBytes))
if err != nil {
return nil, err
}
newRequest.Method = pair.Request.Method
newRequest.Header = pair.Request.Headers
if pair.Request.GetRawQuery() == "" {
// rawQuery is empty if middleware is applied, as unexported fields are not marshal, hence re-encoding of the query params is needed here
t := &url.URL{Path: pair.Request.QueryString()}
newRequest.URL.RawQuery = t.String()
} else {
// otherwise we use the original raw query for pass-through
newRequest.URL.RawQuery = pair.Request.GetRawQuery()
}
return newRequest, nil
}
// ReconstructResponse changes original response with details provided in Constructor Payload.Response
func ReconstructResponse(request *http.Request, pair models.RequestResponsePair) *http.Response {
response := &http.Response{}
response.Request = request
response.ContentLength = int64(len(pair.Response.Body))
response.Body = ioutil.NopCloser(strings.NewReader(pair.Response.Body))
response.StatusCode = pair.Response.Status
response.Status = http.StatusText(pair.Response.Status)
headers := make(http.Header)
// Make copy to prevent modifying the simulation
for k, v := range pair.Response.Headers {
headers[k] = v
}
if keys, present := headers["Trailer"]; present {
response.Trailer = make(http.Header)
for _, key := range keys {
response.Trailer[key] = headers[key]
delete(headers, key)
}
delete(headers, "Trailer")
}
response.Header = headers
if response.ContentLength > 0 && response.Header.Get("Content-Length") == "" && response.Header.Get("Transfer-Encoding") == "" {
response.Header.Set("Content-Length", fmt.Sprintf("%v", response.ContentLength))
}
return response
}
func GetRequestLogFields(request *models.RequestDetails) *log.Fields {
if request == nil {
return &log.Fields{
"error": "nil request",
}
}
return &log.Fields{
"method": request.Method,
"scheme": request.Scheme,
"destination": request.Destination,
"path": request.Path,
"query": request.Query,
"headers": request.Headers,
"body": request.Body,
}
}
func GetResponseLogFields(response *models.ResponseDetails) *log.Fields {
if response == nil || response.Status == 0 {
return &log.Fields{
"error": "nil response",
}
}
return &log.Fields{
"body": response.Body,
"headers": response.Headers,
"status": response.Status,
}
}
func ReturnErrorAndLog(request *http.Request, err error, pair *models.RequestResponsePair, msg, mode string) (ProcessResult, error) {
log.WithFields(log.Fields{
"error": err.Error(),
"mode": mode,
"request": GetRequestLogFields(&pair.Request),
"response": GetResponseLogFields(&pair.Response),
}).Error(msg)
return ErrorResponse(request, err, msg), err
}
func ErrorResponse(req *http.Request, err error, msg string) ProcessResult {
return newProcessResult(goproxy.NewResponse(req,
goproxy.ContentTypeText, http.StatusBadGateway,
fmt.Sprintf("Hoverfly Error!\n\n%s\n\nGot error: %s", msg, err.Error())), 0, nil)
}