-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.go
215 lines (179 loc) · 4.6 KB
/
index.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package httpclient
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/rendau/dop/adapters/client/httpc"
"github.com/rendau/dop/adapters/logger"
"github.com/rendau/dop/dopErrs"
)
type St struct {
lg logger.Lite
opts *httpc.OptionsSt
}
func New(lg logger.Lite, opts *httpc.OptionsSt) *St {
res := &St{
lg: lg,
}
res.SetOptions(opts)
return res
}
func (c *St) GetOptions() *httpc.OptionsSt {
return c.opts
}
func (c *St) SetOptions(opts *httpc.OptionsSt) {
if opts.Uri != "" {
opts.Uri = strings.TrimRight(opts.Uri, "/") + "/"
}
c.opts = opts
}
func (c *St) Send(opts *httpc.OptionsSt) (*httpc.RespSt, error) {
var err error
opts = c.opts.GetMergedWith(opts)
resp := &httpc.RespSt{ReqOpts: opts, Lg: c.lg}
// ReqObj
if opts.ReqStream == nil {
if opts.ReqObj != nil {
if len(opts.Headers.Values("Content-Type")) == 0 {
opts.Headers["Content-Type"] = []string{"application/json"}
}
opts.ReqBody, err = json.Marshal(opts.ReqObj)
if err != nil {
c.lg.Errorw(opts.LogPrefix+"Fail to marshal json", err)
return resp, err
}
}
}
// RepObj
if opts.RepObj != nil {
if len(opts.Headers.Values("Accept")) == 0 {
opts.Headers["Accept"] = []string{"application/json"}
}
}
if opts.HasLogFlag(httpc.LogRequest) {
resp.LogInfo("Request: " + opts.Uri)
}
for i := opts.RetryCount; i >= 0; i-- {
err = c.send(opts, resp)
if err == nil { // if no network error
if opts.ReqStream != nil { // not retry for stream
break
}
if resp.StatusCodeSuccess { // not retry for success
break
}
if resp.StatusCode < 500 { // not retry for "< 500" errors
break
}
}
if i > 0 {
time.Sleep(opts.RetryInterval)
}
}
if err == nil {
err = c.handleRespBadStatusCode(resp)
if err == nil {
// RepObj
if len(resp.BodyRaw) > 0 && resp.ReqOpts.RepObj != nil {
err = json.Unmarshal(resp.BodyRaw, resp.ReqOpts.RepObj)
if err != nil {
if !resp.ReqOpts.HasLogFlag(httpc.NoLogError) {
resp.LogError("Fail to unmarshal body", err)
}
return resp, err
}
}
if opts.HasLogFlag(httpc.LogResponse) {
resp.LogInfo("Response: " + opts.Uri)
}
}
} else {
if !opts.HasLogFlag(httpc.NoLogError) {
resp.LogError("Fail to send http-request", err)
}
}
return resp, err
}
func (c *St) send(opts *httpc.OptionsSt, resp *httpc.RespSt) error {
var err error
resp.Reset()
var req *http.Request
var reqStream io.Reader
if opts.ReqStream != nil {
reqStream = opts.ReqStream
} else if len(opts.ReqBody) > 0 {
reqStream = bytes.NewReader(opts.ReqBody)
}
if opts.Timeout > 0 {
ctx, cancel := context.WithTimeout(context.Background(), opts.Timeout)
defer cancel()
req, err = http.NewRequestWithContext(ctx, opts.Method, opts.Uri, reqStream)
} else {
req, err = http.NewRequest(opts.Method, opts.Uri, reqStream)
}
if err != nil {
return fmt.Errorf("fail to create http-request: %w", err)
}
// headers
if len(opts.Headers) > 0 {
req.Header = opts.Headers
}
// params
if len(opts.Params) > 0 {
req.URL.RawQuery = opts.Params.Encode()
}
// Basic auth
if opts.BasicAuthCreds != nil {
req.SetBasicAuth(opts.BasicAuthCreds.Username, opts.BasicAuthCreds.Password)
}
if opts.ReqClose {
req.Close = true
}
// Do request
rep, err := opts.Client.Do(req)
if err != nil {
return fmt.Errorf("fail to do http-request: %w", err)
}
resp.StatusCode = rep.StatusCode
resp.StatusCodeSuccess = rep.StatusCode >= http.StatusOK && rep.StatusCode < http.StatusMultipleChoices
resp.Headers = rep.Header
if opts.RepStream && resp.StatusCodeSuccess {
resp.Stream = rep.Body
} else {
defer rep.Body.Close()
resp.BodyRaw, err = io.ReadAll(rep.Body)
if err != nil {
return fmt.Errorf("fail to read response body: %w", err)
}
}
return nil
}
func (c *St) handleRespBadStatusCode(resp *httpc.RespSt) error {
if resp.StatusCode > 0 && !resp.StatusCodeSuccess {
if sObj, ok := resp.ReqOpts.StatusRepObj[resp.StatusCode]; ok {
if len(resp.BodyRaw) > 0 {
err := json.Unmarshal(resp.BodyRaw, sObj)
if err != nil {
if !resp.ReqOpts.HasLogFlag(httpc.NoLogError) {
resp.LogError("Fail to unmarshal body", err)
}
return err
}
}
} else if !resp.ReqOpts.HasLogFlag(httpc.NoLogError) && !resp.ReqOpts.HasLogFlag(httpc.NoLogBadStatus) {
switch {
case resp.StatusCode == 401 && resp.ReqOpts.HasLogFlag(httpc.NoLogNotAuthorized):
case resp.StatusCode == 403 && resp.ReqOpts.HasLogFlag(httpc.NoLogPermissionDenied):
default:
resp.LogError("Bad status code", dopErrs.BadStatusCode)
}
}
return dopErrs.BadStatusCode
}
return nil
}