helpers.MakeRequestCapturingTestServer   A
last analyzed

Complexity

Conditions 4

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
dl 0
loc 18
rs 9.75
c 0
b 0
f 0
nop 3
1
package helpers
2
3
import (
4
	"bytes"
5
	"context"
6
	"io/ioutil"
7
	"net/http"
8
	"net/http/httptest"
9
)
10
11
// MakeTestServer creates an api server for testing
12
func MakeTestServer(responseCode int, body []byte) *httptest.Server {
13
	return httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
14
		res.WriteHeader(responseCode)
15
		_, err := res.Write(body)
16
		if err != nil {
17
			panic(err)
18
		}
19
	}))
20
}
21
22
// MakeRequestCapturingTestServer creates an api server that captures the request object
23
func MakeRequestCapturingTestServer(responseCode int, response []byte, request *http.Request) *httptest.Server {
24
	return httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, req *http.Request) {
25
		clonedRequest := req.Clone(context.Background())
26
27
		// clone body
28
		body, err := ioutil.ReadAll(req.Body)
29
		if err != nil {
30
			panic(err)
31
		}
32
		req.Body = ioutil.NopCloser(bytes.NewReader(body))
33
		clonedRequest.Body = ioutil.NopCloser(bytes.NewReader(body))
34
35
		*request = *clonedRequest
36
37
		responseWriter.WriteHeader(responseCode)
38
		_, err = responseWriter.Write(response)
39
		if err != nil {
40
			panic(err)
41
		}
42
	}))
43
}
44