-
Notifications
You must be signed in to change notification settings - Fork 17
/
mocking.go
51 lines (44 loc) · 1.13 KB
/
mocking.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
package easypost
import (
"io"
"io/ioutil"
"net/http"
"regexp"
"strings"
)
type MockRequestMatchRule struct {
Method string
UrlRegexPattern string
}
type MockRequestResponseInfo struct {
StatusCode int
Body string
}
func (r *MockRequestResponseInfo) MockBody() io.ReadCloser {
return ioutil.NopCloser(strings.NewReader(r.Body))
}
type MockRequest struct {
MatchRule MockRequestMatchRule
ResponseInfo MockRequestResponseInfo
}
func (r *MockRequestResponseInfo) AsResponse() *http.Response {
return &http.Response{
Status: http.StatusText(r.StatusCode),
StatusCode: r.StatusCode,
Body: r.MockBody(),
ContentLength: int64(len(r.Body)),
Header: nil,
Request: nil,
}
}
func (c *Client) findMatchingMockRequest(req *http.Request) *http.Response {
for _, mockReq := range c.MockRequests {
url := req.URL.String()
methodMatch := mockReq.MatchRule.Method == "" || mockReq.MatchRule.Method == req.Method
urlMatch, _ := regexp.MatchString(mockReq.MatchRule.UrlRegexPattern, url)
if methodMatch && urlMatch {
return mockReq.ResponseInfo.AsResponse()
}
}
return nil
}