-
Notifications
You must be signed in to change notification settings - Fork 78
/
http.go
42 lines (37 loc) · 937 Bytes
/
http.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
package http
import (
"bytes"
"io"
"net/http"
"strconv"
)
// NewTestClient returns *http.Client with Transport replaced to avoid making real calls
func newHTTPTestClient(fn roundTripFunc) *http.Client {
return &http.Client{
Transport: fn,
}
}
func MakeHTTPTestClient(config map[string]map[string]string) *http.Client {
return newHTTPTestClient(func(req *http.Request) *http.Response {
resp := &http.Response{}
for k, v := range config {
if k == req.URL.String() {
code, _ := strconv.Atoi(v["code"])
resp = &http.Response{
StatusCode: code,
Header: make(http.Header),
}
if body, ok := v["body"]; ok {
resp.Body = io.NopCloser(bytes.NewBufferString(body))
}
}
}
return resp
})
}
// roundTripFunc .
type roundTripFunc func(req *http.Request) *http.Response
// RoundTrip .
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}