This repository has been archived by the owner on Nov 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
httpc.go
109 lines (88 loc) · 1.9 KB
/
httpc.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package httpc
import (
"context"
"io"
"io/ioutil"
"net/http"
"net/url"
)
// @author valor.
// PackedReq is a struct used to define the HTTP request
type PackedReq struct {
// if nil, use global.defaultHttpClient
Client *http.Client
Ctx context.Context
URL string
Method string
Header map[string]string
// if nil, use PublisherNoBody
ReqBodyPublisher ReqBodyPublisher
// if nil, use RespBodyNoHandle
RespBodyHandler RespBodyHandler
}
func (r PackedReq) getBlankHttpRequest() (req *http.Request, err error) {
if r.Ctx == nil {
req, err = http.NewRequest("", "", nil)
} else {
req, err = http.NewRequestWithContext(r.Ctx, "", "", nil)
}
return
}
// Send the HTTP request
func (r PackedReq) Send() (interface{}, error) {
req, err := r.getBlankHttpRequest()
if err != nil {
return nil, err
}
// set URL
u, err := url.Parse(r.URL)
if err != nil {
return nil, err
}
req.URL = u
// set method
req.Method = r.Method
// request body
if r.ReqBodyPublisher == nil {
r.ReqBodyPublisher = PublisherNoBody{}
}
body := r.ReqBodyPublisher.Subscribe()
if body.Content != nil {
rc, ok := body.Content.(io.ReadCloser)
if !ok {
rc = ioutil.NopCloser(body.Content)
}
req.Body = rc
req.ContentLength = body.Length
req.Header.Set("Content-Type", body.Type)
}
// set user agent
req.Header.Set("User-Agent", "httpc v"+version+" @github.com:valord577")
// set header
if len(r.Header) > 0 {
for k, v := range r.Header {
req.Header.Set(k, v)
}
}
// set HTTP client
if r.Client == nil {
r.Client = defaultHttpClient
}
// do HTTP request
resp, err := r.Client.Do(req)
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
// response body
if r.RespBodyHandler == nil {
r.RespBodyHandler = RespBodyNoHandle{}
}
resBody, err := r.RespBodyHandler.Apply(resp.Body)
if err != nil {
return nil, err
}
return resBody, nil
}