File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change 1+ package request
2+
3+ import (
4+ "net/http"
5+ "sync"
6+ "time"
7+ )
8+
9+ type Client struct {
10+ // BaseURL will be prepended to all request URL unless URL is absolute.
11+ BaseURL string
12+ // Headers are custom headers to be sent.
13+ Headers http.Header
14+ // clientPool is for save http.Client instances.
15+ clientPool sync.Pool
16+ // timeout specifies the time before the request times out.
17+ timeout time.Duration
18+ }
19+
20+ type Config struct {
21+ // BaseURL will be prepended to all request URL unless URL is absolute.
22+ BaseURL string
23+ // Timeout is request timeout in milliseconds.
24+ Timeout int
25+ // Headers are custom headers to be sent.
26+ Headers map [string ][]string
27+ }
28+
29+ var defaultClient * Client
30+
31+ // New creates and returns a new Client instance.
32+ func New (config ... Config ) * Client {
33+ cli := new (Client )
34+
35+ cli .Headers = make (http.Header )
36+ cli .clientPool = sync.Pool {
37+ New : func () any {
38+ return http.Client {}
39+ },
40+ }
41+
42+ if len (config ) > 0 {
43+ cfg := config [0 ]
44+
45+ cli .BaseURL = cfg .BaseURL
46+ if cfg .Timeout > 0 {
47+ cli .SetTimeout (cfg .Timeout )
48+ }
49+ cli .setHeader (cfg .Headers )
50+ }
51+
52+ return cli
53+ }
54+
55+ // SetTimeout sets client's timeout with a number in milliseconds.
56+ func (cli * Client ) SetTimeout (timeout int ) {
57+ cli .timeout = time .Duration (timeout ) * time .Millisecond
58+ }
59+
60+ // setHeader initializes client's Headers field from config.
61+ func (cli * Client ) setHeader (headers map [string ][]string ) {
62+ for k , v := range headers {
63+ if len (v ) > 0 {
64+ cli .Headers [k ] = make ([]string , len (v ))
65+ copy (cli .Headers [k ], v )
66+ } else {
67+ cli .Headers [k ] = nil
68+ }
69+ }
70+ }
71+
72+ func init () {
73+ defaultClient = New ()
74+ }
You can’t perform that action at this time.
0 commit comments