-
Notifications
You must be signed in to change notification settings - Fork 10
/
request_sender.go
67 lines (55 loc) · 1.75 KB
/
request_sender.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
package solr
import (
"context"
"io"
"net/http"
)
// RequestSender is an HTTP request sender
type RequestSender interface {
SendRequest(ctx context.Context, method, urlStr,
contentType string, body io.Reader) (*http.Response, error)
}
type basicAuth struct {
username, password string
}
// DefaultRequestSender is the default HTTP request sender
type DefaultRequestSender struct {
httpClient *http.Client
basicAuth *basicAuth
}
var _ RequestSender = (*DefaultRequestSender)(nil)
// NewDefaultRequestSender returns a new DefaultRequestSender
func NewDefaultRequestSender() *DefaultRequestSender {
return &DefaultRequestSender{
httpClient: http.DefaultClient,
}
}
// WithHTTPClient overrides the default HTTP client
func (rs *DefaultRequestSender) WithHTTPClient(httpClient *http.Client) *DefaultRequestSender {
rs.httpClient = httpClient
return rs
}
// WithBasicAuth sets the basic auth credentials
func (rs *DefaultRequestSender) WithBasicAuth(username, password string) *DefaultRequestSender {
rs.basicAuth = &basicAuth{username: username, password: password}
return rs
}
// SendRequest builds and sends the HTTP request
func (rs *DefaultRequestSender) SendRequest(ctx context.Context, httpMethod,
urlStr, contentType string, body io.Reader) (*http.Response, error) {
httpReq, err := http.NewRequestWithContext(ctx, httpMethod, urlStr, body)
if err != nil {
return nil, wrapErr(err, "new http request")
}
httpReq.Header.Add("content-type", contentType)
// include basic auth if available
if rs.basicAuth != nil {
httpReq.SetBasicAuth(rs.basicAuth.username, rs.basicAuth.password)
}
var httpResp *http.Response
httpResp, err = rs.httpClient.Do(httpReq)
if err != nil {
return nil, wrapErr(err, "send http request")
}
return httpResp, nil
}