-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathrequester.go
70 lines (55 loc) · 1.78 KB
/
requester.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
package testflight
import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
)
type Requester struct {
server *httptest.Server
}
func (requester *Requester) Get(route string) *Response {
return requester.performRequest("GET", route, "", "")
}
func (requester *Requester) Post(route, contentType, body string) *Response {
return requester.performRequest("POST", route, contentType, body)
}
func (requester *Requester) Put(route, contentType, body string) *Response {
return requester.performRequest("PUT", route, contentType, body)
}
func (requester *Requester) Patch(route, contentType, body string) *Response {
return requester.performRequest("PATCH", route, contentType, body)
}
func (requester *Requester) Delete(route, contentType, body string) *Response {
return requester.performRequest("DELETE", route, contentType, body)
}
func (requester *Requester) Do(request *http.Request) *Response {
fullUrl, err := url.Parse(requester.httpUrl(request.URL.String()))
if err != nil {
panic(err)
}
request.URL = fullUrl
return requester.sendRequest(request)
}
func (requester *Requester) Url(route string) string {
return requester.server.Listener.Addr().String() + route
}
func (requester *Requester) performRequest(httpAction, route, contentType, body string) *Response {
request, err := http.NewRequest(httpAction, requester.httpUrl(route), strings.NewReader(body))
if err != nil {
panic(err)
}
request.Header.Add("Content-Type", contentType)
return requester.sendRequest(request)
}
func (requester *Requester) sendRequest(request *http.Request) *Response {
client := http.Client{}
response, err := client.Do(request)
if err != nil {
panic(err)
}
return newResponse(response)
}
func (requester *Requester) httpUrl(route string) string {
return "http://" + requester.Url(route)
}