-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest_builder.go
More file actions
94 lines (76 loc) · 1.99 KB
/
Copy pathrequest_builder.go
File metadata and controls
94 lines (76 loc) · 1.99 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package requestbuilder
import (
"errors"
"fmt"
"strings"
)
var (
ErrNoMethodFound = errors.New("Empty Method")
ErrNoUrlFound = errors.New("Empty URL")
ErrNoSupportedMethod = errors.New("unsupported method")
)
var SupportedValidMethods = map[string]bool{
"GET": true,
"POST": true,
"DELETE": true,
"PATCH": true,
"PUT": true,
}
// keeping the Request struct private and exposing only builder struct
type RequestBuilder struct {
requestInProgress request
}
func NewRequestBuilder() *RequestBuilder {
return &RequestBuilder{
requestInProgress: request{
headers: make(map[string]string),
timeoutInSeconds: 30,
method: "GET",
},
}
}
func (rb *RequestBuilder) WithUrl(url string) *RequestBuilder {
rb.requestInProgress.url = url
return rb
}
func (rb *RequestBuilder) WithTimeout(timeout int) *RequestBuilder {
rb.requestInProgress.timeoutInSeconds = timeout
return rb
}
func (rb *RequestBuilder) WithMethod(method string) *RequestBuilder {
rb.requestInProgress.method = strings.ToUpper(method)
return rb
}
func (rb *RequestBuilder) WithBody(body string) *RequestBuilder {
if rb.requestInProgress.method == "GET" {
fmt.Println("Unusual practice detected adding body with GET method")
}
rb.requestInProgress.body = body
return rb
}
func (rb *RequestBuilder) WithHeader(key, val string) *RequestBuilder {
rb.requestInProgress.headers[key] = val
return rb
}
func (rb *RequestBuilder) WithHeaders(mapOfHeader map[string]string) *RequestBuilder {
if mapOfHeader == nil {
mapOfHeader = make(map[string]string)
}
for key, val := range mapOfHeader {
rb.requestInProgress.headers[key] = val
}
return rb
}
func (rb *RequestBuilder) Build() (Request, error) {
if rb.requestInProgress.url == "" {
return nil, ErrNoUrlFound
}
if rb.requestInProgress.method == "" {
return nil, ErrNoMethodFound
}
_, ok := SupportedValidMethods[rb.requestInProgress.method]
if !ok {
return nil, ErrNoSupportedMethod
}
return rb.requestInProgress, nil
}