-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathfactory.go
44 lines (38 loc) · 1.49 KB
/
factory.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
package httpclient
import (
"net/http"
)
// HttpClientFactory is the interface for [http.Client] factories.
type HttpClientFactory interface {
Create(opts ...HttpClientOption) (*http.Client, error)
}
// DefaultHttpClientFactory is the default [HttpClientFactory] implementation.
type DefaultHttpClientFactory struct{}
// NewDefaultHttpClientFactory returns a [DefaultHttpClientFactory], implementing [HttpClientFactory].
func NewDefaultHttpClientFactory() HttpClientFactory {
return &DefaultHttpClientFactory{}
}
// Create returns a new [http.Client], and accepts a list of [HttpClientOption].
// For example:
//
// var client, _ = httpclient.NewDefaultHttpClientFactory().Create()
//
// // equivalent to:
// var client, _ = httpclient.NewDefaultHttpClientFactory().Create(
// httpclient.WithTransport(transport.NewBaseTransport()), // base http transport (optimized)
// httpclient.WithTimeout(30*time.Second), // 30 seconds timeout
// httpclient.WithCheckRedirect(nil), // default redirection checks
// httpclient.WithCookieJar(nil), // default cookie jar
// )
func (f *DefaultHttpClientFactory) Create(options ...HttpClientOption) (*http.Client, error) {
appliedOpts := DefaultHttpClientOptions()
for _, applyOpt := range options {
applyOpt(&appliedOpts)
}
return &http.Client{
Transport: appliedOpts.Transport,
CheckRedirect: appliedOpts.CheckRedirect,
Jar: appliedOpts.Jar,
Timeout: appliedOpts.Timeout,
}, nil
}