forked from smarty-archives/httpunit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
52 lines (48 loc) · 959 Bytes
/
request.go
File metadata and controls
52 lines (48 loc) · 959 Bytes
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
package httpunit
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
)
type RequestBuilder struct {
Context context.Context
Method string
URL string
Headers http.Header
Body string
JSON interface{}
}
func NewRequestBuilder() *RequestBuilder {
return &RequestBuilder{
Method: http.MethodGet,
URL: "/",
Headers: make(http.Header),
}
}
func (this *RequestBuilder) Build() *http.Request {
request := httptest.NewRequest(this.Method, this.URL, this.body())
if this.Context != nil {
request = request.WithContext(this.Context)
}
for key, values := range this.Headers {
request.Header[key] = values
}
return request
}
func (this *RequestBuilder) body() (body io.Reader) {
if len(this.Body) > 0 {
return strings.NewReader(this.Body)
}
if this.JSON == nil {
return nil
}
raw, err := json.Marshal(this.JSON)
if err != nil {
panic(err)
}
return bytes.NewReader(raw)
}