-
Notifications
You must be signed in to change notification settings - Fork 11
/
rest_client.go
296 lines (238 loc) · 7.93 KB
/
rest_client.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package restclient
import (
"bytes"
"encoding/xml"
"fmt"
"github.com/aliyun/aliyun-odps-go-sdk/odps/account"
"github.com/aliyun/aliyun-odps-go-sdk/odps/common"
"github.com/pkg/errors"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
)
// Todo 请求方法需要重构,加入header参数
const (
DefaultHttpTimeout = 5
DefaultTcpConnectionTimeout = 30
)
type RestClient struct {
account.Account
// It is the total time from the tcp connection to http response.
// the default value is 0, represents no timeout
HttpTimeout time.Duration
TcpConnectionTimeout time.Duration
DisableCompression bool
_client *http.Client
defaultProject string
endpoint string
userAgent string
}
func NewOdpsRestClient(a account.Account, endpoint string) RestClient {
var client = RestClient{
Account: a,
endpoint: endpoint,
HttpTimeout: DefaultHttpTimeout * time.Second,
TcpConnectionTimeout: DefaultTcpConnectionTimeout * time.Second,
DisableCompression: true,
}
return client
}
func LoadEndpointFromEnv() string {
endpoint, _ := os.LookupEnv("odps_endpoint")
return endpoint
}
func (client *RestClient) SetDefaultProject(projectName string) {
client.defaultProject = projectName
}
func (client *RestClient) SetUserAgent(userAgent string) {
client.userAgent = userAgent
}
func (client *RestClient) UserAgent() string {
if client.userAgent != "" {
return client.userAgent
}
return common.UserAgentValue
}
func (client *RestClient) Endpoint() string {
return client.endpoint
}
func (client *RestClient) client() *http.Client {
if client._client != nil {
return client._client
}
var transport = http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: client.TcpConnectionTimeout,
KeepAlive: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: false,
DisableKeepAlives: true,
DisableCompression: client.DisableCompression,
}
client._client = &http.Client{
Transport: &transport,
Timeout: client.HttpTimeout,
}
return client._client
}
func (client *RestClient) NewRequest(method, resource string, body io.Reader) (*http.Request, error) {
var urlStr = fmt.Sprintf(
"%s/%s",
strings.TrimRight(client.Endpoint(), "/"),
strings.TrimLeft(resource, "/"))
req, err := http.NewRequest(method, urlStr, body)
return req, errors.WithStack(err)
}
func (client *RestClient) NewRequestWithUrlQuery(method, resource string, body io.Reader, queryArgs url.Values) (*http.Request, error) {
req, err := client.NewRequest(method, resource, body)
if err != nil {
return nil, errors.WithStack(err)
}
if queryArgs != nil {
req.URL.RawQuery = queryArgs.Encode()
}
return req, nil
}
func (client *RestClient) Do(req *http.Request) (*http.Response, error) {
req.Header.Set(common.HttpHeaderUserAgent, common.UserAgentValue)
req.Header.Set(common.HttpHeaderXOdpsUserAgent, client.UserAgent())
gmtTime := time.Now().In(common.GMT).Format(time.RFC1123)
req.Header.Set(common.HttpHeaderDate, gmtTime)
query := req.URL.Query()
_, ok := query["current_project"]
// in go1.17, 下面的语句应该这样写:if !query.Has("curr_project") && client.defaultProject != "" {
// 但values.Has方法是在go1.17才引入的,为了兼容go1.15,所以不用Has方法
if !ok && client.defaultProject != "" {
query.Set("curr_project", client.defaultProject)
}
req.URL.RawQuery = query.Encode()
client.SignRequest(req, client.endpoint)
res, err := client.client().Do(req)
return res, errors.WithStack(err)
}
func (client *RestClient) DoWithParseFunc(req *http.Request, parseFunc func(res *http.Response) error) error {
return client.DoWithParseRes(req, func(res *http.Response) error {
if res.StatusCode < 200 || res.StatusCode >= 300 {
return errors.WithStack(NewHttpNotOk(res))
}
if parseFunc == nil {
return nil
}
return errors.WithStack(parseFunc(res))
})
}
func (client *RestClient) DoWithParseRes(req *http.Request, parseFunc func(res *http.Response) error) error {
res, err := client.Do(req)
if err != nil {
return errors.WithStack(err)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Fatalf("close http error, url=%s", req.URL.String())
}
}(res.Body)
if parseFunc == nil {
return nil
}
return errors.WithStack(parseFunc(res))
}
func (client *RestClient) DoWithModel(req *http.Request, model interface{}) error {
parseFunc := func(res *http.Response) error {
decoder := xml.NewDecoder(res.Body)
return errors.WithStack(decoder.Decode(model))
}
return errors.WithStack(client.DoWithParseFunc(req, parseFunc))
}
func (client *RestClient) GetWithModel(resource string, queryArgs url.Values, model interface{}) error {
req, err := client.NewRequestWithUrlQuery(common.HttpMethod.GetMethod, resource, nil, queryArgs)
if err != nil {
return errors.WithStack(err)
}
return errors.WithStack(client.DoWithModel(req, model))
}
func (client *RestClient) GetWithParseFunc(resource string, queryArgs url.Values, parseFunc func(res *http.Response) error) error {
req, err := client.NewRequestWithUrlQuery(common.HttpMethod.GetMethod, resource, nil, queryArgs)
if err != nil {
return errors.WithStack(err)
}
return errors.WithStack(client.DoWithParseFunc(req, parseFunc))
}
func (client *RestClient) PutWithParseFunc(resource string, queryArgs url.Values, body io.Reader, parseFunc func(res *http.Response) error) error {
req, err := client.NewRequestWithUrlQuery(common.HttpMethod.PutMethod, resource, body, queryArgs)
if err != nil {
return errors.WithStack(err)
}
return errors.WithStack(client.DoWithParseFunc(req, parseFunc))
}
func (client *RestClient) DoXmlWithParseFunc(
method string,
resource string,
queryArgs url.Values,
bodyModel interface{},
parseFunc func(res *http.Response) error) error {
bodyXml, err := xml.Marshal(bodyModel)
if err != nil {
return errors.WithStack(err)
}
req, err := client.NewRequestWithUrlQuery(method, resource, bytes.NewReader(bodyXml), queryArgs)
req.Header.Set(common.HttpHeaderContentType, common.XMLContentType)
if err != nil {
return errors.WithStack(err)
}
return errors.WithStack(client.DoWithParseFunc(req, parseFunc))
}
func (client *RestClient) DoXmlWithParseRes(
method string,
resource string,
queryArgs url.Values,
bodyModel interface{},
parseFunc func(res *http.Response) error) error {
bodyXml, err := xml.Marshal(bodyModel)
if err != nil {
return errors.WithStack(err)
}
req, err := client.NewRequestWithUrlQuery(method, resource, bytes.NewReader(bodyXml), queryArgs)
req.Header.Set(common.HttpHeaderContentType, common.XMLContentType)
if err != nil {
return errors.WithStack(err)
}
return errors.WithStack(client.DoWithParseRes(req, parseFunc))
}
func (client *RestClient) DoXmlWithModel(
method string,
resource string,
queryArgs url.Values,
bodyModel interface{},
resModel interface{}) error {
parseFunc := func(res *http.Response) error {
decoder := xml.NewDecoder(res.Body)
if resModel == nil {
return nil
}
return errors.WithStack(decoder.Decode(resModel))
}
err := client.DoXmlWithParseFunc(method, resource, queryArgs, bodyModel, parseFunc)
return errors.WithStack(err)
}