forked from denverdino/aliyungo
/
client.go
833 lines (699 loc) · 22.8 KB
/
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
package common
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/opentracing/opentracing-go/ext"
"github.com/opentracing/opentracing-go"
"github.com/reedchan7/aliyungo/util"
)
// RemovalPolicy.N add index to array item
// RemovalPolicy=["a", "b"] => RemovalPolicy.1="a" RemovalPolicy.2="b"
type FlattenArray []string
// string contains underline which will be replaced with dot
// SystemDisk_Category => SystemDisk.Category
type UnderlineString string
// A Client represents a client of ECS services
type Client struct {
AccessKeyId string // Access Key Id
AccessKeySecret string // Access Key Secret
securityToken string
debug bool
httpClient *http.Client
endpoint string
version string
serviceCode string
regionID Region
businessInfo string
userAgent string
disableTrace bool
span opentracing.Span
logger *Logger
}
// Initialize properties of a client instance
func (client *Client) Init(endpoint, version, accessKeyId, accessKeySecret string) {
client.AccessKeyId = accessKeyId
ak := accessKeySecret
if !strings.HasSuffix(ak, "&") {
ak += "&"
}
client.AccessKeySecret = ak
client.InitClient()
client.endpoint = endpoint
client.version = version
}
// Initialize properties of a client instance including regionID
func (client *Client) NewInit(endpoint, version, accessKeyId, accessKeySecret, serviceCode string, regionID Region) {
client.Init(endpoint, version, accessKeyId, accessKeySecret)
client.serviceCode = serviceCode
client.regionID = regionID
}
// Initialize properties of a client instance including regionID
// only for hz regional Domain
func (client *Client) NewInit4RegionalDomain(endpoint, version, accessKeyId, accessKeySecret, serviceCode string, regionID Region) {
client.Init(endpoint, version, accessKeyId, accessKeySecret)
client.serviceCode = serviceCode
client.regionID = regionID
client.setEndpoint4RegionalDomain(client.regionID, client.serviceCode, client.AccessKeyId, client.AccessKeySecret, client.securityToken)
}
// Intialize client object when all properties are ready
func (client *Client) InitClient() *Client {
client.debug = false
// create DefaultTransport manully, because transport doesn't has clone method in go 1.10
t := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
handshakeTimeoutStr, ok := os.LookupEnv("TLSHandshakeTimeout")
if ok {
handshakeTimeout, err := strconv.Atoi(handshakeTimeoutStr)
if err != nil {
log.Printf("Get TLSHandshakeTimeout from env error: %v.", err)
} else {
t.TLSHandshakeTimeout = time.Duration(handshakeTimeout) * time.Second
}
}
responseHeaderTimeoutStr, ok := os.LookupEnv("ResponseHeaderTimeout")
if ok {
responseHeaderTimeout, err := strconv.Atoi(responseHeaderTimeoutStr)
if err != nil {
log.Printf("Get ResponseHeaderTimeout from env error: %v.", err)
} else {
t.ResponseHeaderTimeout = time.Duration(responseHeaderTimeout) * time.Second
}
}
expectContinueTimeoutStr, ok := os.LookupEnv("ExpectContinueTimeout")
if ok {
expectContinueTimeout, err := strconv.Atoi(expectContinueTimeoutStr)
if err != nil {
log.Printf("Get ExpectContinueTimeout from env error: %v.", err)
} else {
t.ExpectContinueTimeout = time.Duration(expectContinueTimeout) * time.Second
}
}
idleConnTimeoutStr, ok := os.LookupEnv("IdleConnTimeout")
if ok {
idleConnTimeout, err := strconv.Atoi(idleConnTimeoutStr)
if err != nil {
log.Printf("Get IdleConnTimeout from env error: %v.", err)
} else {
t.IdleConnTimeout = time.Duration(idleConnTimeout) * time.Second
}
}
client.httpClient = &http.Client{
Transport: t,
}
httpTimeoutStr, ok := os.LookupEnv("HttpTimeout")
if ok {
httpTimeout, err := strconv.Atoi(httpTimeoutStr)
if err != nil {
log.Printf("Get HttpTimeout from env error: %v.", err)
} else {
client.httpClient.Timeout = time.Duration(httpTimeout) * time.Second
}
}
return client
}
// Intialize client object when all properties are ready
// only for regional domain hz
func (client *Client) InitClient4RegionalDomain() *Client {
client.InitClient()
// set endpoint
client.setEndpoint4RegionalDomain(client.regionID, client.serviceCode, client.AccessKeyId, client.AccessKeySecret, client.securityToken)
return client
}
func (client *Client) NewInitForAssumeRole(endpoint, version, accessKeyId, accessKeySecret, serviceCode string, regionID Region, securityToken string) {
client.NewInit(endpoint, version, accessKeyId, accessKeySecret, serviceCode, regionID)
client.securityToken = securityToken
}
// getLocationEndpoint
func (client *Client) getEndpointByLocation() string {
locationClient := NewLocationClient(client.AccessKeyId, client.AccessKeySecret, client.securityToken)
locationClient.SetDebug(true)
return locationClient.DescribeOpenAPIEndpoint(client.regionID, client.serviceCode)
}
// NewClient using location service
func (client *Client) setEndpointByLocation(region Region, serviceCode, accessKeyId, accessKeySecret, securityToken string) {
locationClient := NewLocationClient(accessKeyId, accessKeySecret, securityToken)
locationClient.SetDebug(true)
ep := locationClient.DescribeOpenAPIEndpoint(region, serviceCode)
if ep != "" {
client.endpoint = ep
}
}
// Get openapi endpoint accessed by ecs instance.
// For some UnitRegions, the endpoint pattern is https://[product].[regionid].aliyuncs.com
// For some CentralRegions, the endpoint pattern is https://[product].vpc-proxy.aliyuncs.com
// The other region, the endpoint pattern is https://[product]-vpc.[regionid].aliyuncs.com
func (client *Client) setEndpoint4RegionalDomain(region Region, serviceCode, accessKeyId, accessKeySecret, securityToken string) {
if endpoint, ok := CentralDomainServices[serviceCode]; ok {
client.endpoint = fmt.Sprintf("https://%s", endpoint)
return
}
for _, service := range RegionalDomainServices {
if service == serviceCode {
if ep, ok := UnitRegions[region]; ok {
client.endpoint = fmt.Sprintf("https://%s.%s.aliyuncs.com", serviceCode, ep)
return
}
client.endpoint = fmt.Sprintf("https://%s%s.%s.aliyuncs.com", serviceCode, "-vpc", region)
return
}
}
locationClient := NewLocationClient(accessKeyId, accessKeySecret, securityToken)
locationClient.SetDebug(true)
ep := locationClient.DescribeOpenAPIEndpoint(region, serviceCode)
if ep != "" {
client.endpoint = ep
}
}
// Ensure all necessary properties are valid
func (client *Client) ensureProperties() error {
var msg string
if client.endpoint == "" {
msg = fmt.Sprintf("endpoint cannot be empty!")
} else if client.version == "" {
msg = fmt.Sprintf("version cannot be empty!")
} else if client.AccessKeyId == "" {
msg = fmt.Sprintf("AccessKeyId cannot be empty!")
} else if client.AccessKeySecret == "" {
msg = fmt.Sprintf("AccessKeySecret cannot be empty!")
}
if msg != "" {
return errors.New(msg)
}
return nil
}
// ----------------------------------------------------
// WithXXX methods
// ----------------------------------------------------
// WithEndpoint sets custom endpoint
func (client *Client) WithEndpoint(endpoint string) *Client {
client.SetEndpoint(endpoint)
return client
}
// WithVersion sets custom version
func (client *Client) WithVersion(version string) *Client {
client.SetVersion(version)
return client
}
// WithRegionID sets Region ID
func (client *Client) WithRegionID(regionID Region) *Client {
client.SetRegionID(regionID)
return client
}
// WithServiceCode sets serviceCode
func (client *Client) WithServiceCode(serviceCode string) *Client {
client.SetServiceCode(serviceCode)
return client
}
// WithAccessKeyId sets new AccessKeyId
func (client *Client) WithAccessKeyId(id string) *Client {
client.SetAccessKeyId(id)
return client
}
// WithAccessKeySecret sets new AccessKeySecret
func (client *Client) WithAccessKeySecret(secret string) *Client {
client.SetAccessKeySecret(secret)
return client
}
// WithSecurityToken sets securityToken
func (client *Client) WithSecurityToken(securityToken string) *Client {
client.SetSecurityToken(securityToken)
return client
}
// WithDebug sets debug mode to log the request/response message
func (client *Client) WithDebug(debug bool) *Client {
client.SetDebug(debug)
return client
}
// WithBusinessInfo sets business info to log the request/response message
func (client *Client) WithBusinessInfo(businessInfo string) *Client {
client.SetBusinessInfo(businessInfo)
return client
}
// WithUserAgent sets user agent to the request/response message
func (client *Client) WithUserAgent(userAgent string) *Client {
client.SetUserAgent(userAgent)
return client
}
// WithUserAgent sets user agent to the request/response message
func (client *Client) WithDisableTrace(disableTrace bool) *Client {
client.SetDisableTrace(disableTrace)
return client
}
// WithUserAgent sets user agent to the request/response message
func (client *Client) WithSpan(span opentracing.Span) *Client {
client.SetSpan(span)
return client
}
// ----------------------------------------------------
// SetXXX methods
// ----------------------------------------------------
// SetEndpoint sets custom endpoint
func (client *Client) SetEndpoint(endpoint string) {
client.endpoint = endpoint
}
func (client *Client) GetEndpoint() string {
return client.endpoint
}
// SetEndpoint sets custom version
func (client *Client) SetVersion(version string) {
client.version = version
}
// SetEndpoint sets Region ID
func (client *Client) SetRegionID(regionID Region) {
client.regionID = regionID
}
// SetServiceCode sets serviceCode
func (client *Client) SetServiceCode(serviceCode string) {
client.serviceCode = serviceCode
}
// SetAccessKeyId sets new AccessKeyId
func (client *Client) SetAccessKeyId(id string) {
client.AccessKeyId = id
}
// SetAccessKeySecret sets new AccessKeySecret
func (client *Client) SetAccessKeySecret(secret string) {
client.AccessKeySecret = secret + "&"
}
// SetDebug sets debug mode to log the request/response message
func (client *Client) SetDebug(debug bool) {
client.debug = debug
}
// SetBusinessInfo sets business info to log the request/response message
func (client *Client) SetBusinessInfo(businessInfo string) {
if strings.HasPrefix(businessInfo, "/") {
client.businessInfo = businessInfo
} else if businessInfo != "" {
client.businessInfo = "/" + businessInfo
}
}
// SetUserAgent sets user agent to the request/response message
func (client *Client) SetUserAgent(userAgent string) {
client.userAgent = userAgent
}
// set SecurityToken
func (client *Client) SetSecurityToken(securityToken string) {
client.securityToken = securityToken
}
// SetTransport sets transport to the http client
func (client *Client) SetTransport(transport http.RoundTripper) {
if client.httpClient == nil {
client.httpClient = &http.Client{}
}
client.httpClient.Transport = transport
}
// SetDisableTrace close trace mode
func (client *Client) SetDisableTrace(disableTrace bool) {
client.disableTrace = disableTrace
}
// SetSpan set the parent span
func (client *Client) SetSpan(span opentracing.Span) {
client.span = span
}
func (client *Client) initEndpoint() error {
// if set any value to "CUSTOMIZED_ENDPOINT" could skip location service.
// example: export CUSTOMIZED_ENDPOINT=true
if os.Getenv("CUSTOMIZED_ENDPOINT") != "" {
return nil
}
if client.endpoint != "" {
return nil
}
if client.serviceCode != "" && client.regionID != "" {
endpoint := client.getEndpointByLocation()
if endpoint == "" {
return GetCustomError("InvalidEndpoint", "endpoint is empty,pls check")
}
client.endpoint = endpoint
}
return nil
}
// Invoke sends the raw HTTP request for ECS services
func (client *Client) Invoke(action string, args interface{}, response interface{}) (err error) {
if err := client.ensureProperties(); err != nil {
return err
}
// log request
fieldMap := make(map[string]string)
initLogMsg(fieldMap)
defer func() {
client.printLog(fieldMap, err)
}()
request := Request{}
request.init(client.version, action, client.AccessKeyId, client.securityToken, client.regionID)
query := util.ConvertToQueryValues(request)
util.SetQueryValues(args, &query)
// Sign request
signature := util.CreateSignatureForRequest(ECSRequestMethod, &query, client.AccessKeySecret)
// Generate the request URL
requestURL := client.endpoint + "?" + query.Encode() + "&Signature=" + url.QueryEscape(signature)
httpReq, err := http.NewRequest(ECSRequestMethod, requestURL, nil)
if err != nil {
return GetClientError(err)
}
// TODO move to util and add build val flag
httpReq.Header.Set("X-SDK-Client", `AliyunGO/`+Version+client.businessInfo)
httpReq.Header.Set("User-Agent", httpReq.UserAgent()+" "+client.userAgent)
// Set tracer
var span opentracing.Span
if ok := opentracing.IsGlobalTracerRegistered(); ok && !client.disableTrace {
tracer := opentracing.GlobalTracer()
var rootCtx opentracing.SpanContext
if client.span != nil {
rootCtx = client.span.Context()
}
span = tracer.StartSpan(
"AliyunGO-"+request.Action,
opentracing.ChildOf(rootCtx),
opentracing.Tag{string(ext.Component), "AliyunGO"},
opentracing.Tag{"ActionName", request.Action})
defer span.Finish()
tracer.Inject(
span.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(httpReq.Header))
}
putMsgToMap(fieldMap, httpReq)
t0 := time.Now()
fieldMap["{start_time}"] = t0.Format("2006-01-02 15:04:05")
httpResp, err := client.httpClient.Do(httpReq)
t1 := time.Now()
fieldMap["{cost}"] = t1.Sub(t0).String()
if err != nil {
if span != nil {
ext.LogError(span, err)
}
return GetClientError(err)
}
fieldMap["{code}"] = strconv.Itoa(httpResp.StatusCode)
fieldMap["{res_headers}"] = TransToString(httpResp.Header)
statusCode := httpResp.StatusCode
if client.debug {
log.Printf("Invoke %s %s %d (%v)", ECSRequestMethod, requestURL, statusCode, t1.Sub(t0))
}
if span != nil {
ext.HTTPStatusCode.Set(span, uint16(httpResp.StatusCode))
}
defer httpResp.Body.Close()
body, err := ioutil.ReadAll(httpResp.Body)
fieldMap["{res_body}"] = string(body)
if err != nil {
return GetClientError(err)
}
if client.debug {
var prettyJSON bytes.Buffer
err = json.Indent(&prettyJSON, body, "", " ")
if err != nil {
log.Printf("Failed in json.Indent: %v\n", err)
} else {
log.Printf("JSON body: %s\n", prettyJSON.String())
}
}
if statusCode >= 400 && statusCode <= 599 {
errorResponse := ErrorResponse{}
err = json.Unmarshal(body, &errorResponse)
if err != nil {
log.Printf("Failed in json.Unmarshal: %v\n", err)
}
ecsError := &Error{
ErrorResponse: errorResponse,
StatusCode: statusCode,
}
return ecsError
}
err = json.Unmarshal(body, response)
// log.Printf("%++v", response)
if err != nil {
return GetClientError(err)
}
return nil
}
// Invoke sends the raw HTTP request for ECS services
func (client *Client) InvokeByFlattenMethod(action string, args interface{}, response interface{}) (err error) {
if err := client.ensureProperties(); err != nil {
return err
}
// log request
fieldMap := make(map[string]string)
initLogMsg(fieldMap)
defer func() {
client.printLog(fieldMap, err)
}()
// init endpoint
if err := client.initEndpoint(); err != nil {
return err
}
request := Request{}
request.init(client.version, action, client.AccessKeyId, client.securityToken, client.regionID)
query := util.ConvertToQueryValues(request)
util.SetQueryValueByFlattenMethod(args, &query)
// Sign request
signature := util.CreateSignatureForRequest(ECSRequestMethod, &query, client.AccessKeySecret)
// Generate the request URL
requestURL := client.endpoint + "?" + query.Encode() + "&Signature=" + url.QueryEscape(signature)
httpReq, err := http.NewRequest(ECSRequestMethod, requestURL, nil)
if err != nil {
return GetClientError(err)
}
// TODO move to util and add build val flag
httpReq.Header.Set("X-SDK-Client", `AliyunGO/`+Version+client.businessInfo)
httpReq.Header.Set("User-Agent", httpReq.UserAgent()+" "+client.userAgent)
// Set tracer
var span opentracing.Span
if ok := opentracing.IsGlobalTracerRegistered(); ok && !client.disableTrace {
tracer := opentracing.GlobalTracer()
var rootCtx opentracing.SpanContext
if client.span != nil {
rootCtx = client.span.Context()
}
span = tracer.StartSpan(
"AliyunGO-"+request.Action,
opentracing.ChildOf(rootCtx),
opentracing.Tag{string(ext.Component), "AliyunGO"},
opentracing.Tag{"ActionName", request.Action})
defer span.Finish()
tracer.Inject(
span.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(httpReq.Header))
}
putMsgToMap(fieldMap, httpReq)
t0 := time.Now()
fieldMap["{start_time}"] = t0.Format("2006-01-02 15:04:05")
httpResp, err := client.httpClient.Do(httpReq)
t1 := time.Now()
fieldMap["{cost}"] = t1.Sub(t0).String()
if err != nil {
if span != nil {
ext.LogError(span, err)
}
return GetClientError(err)
}
fieldMap["{code}"] = strconv.Itoa(httpResp.StatusCode)
fieldMap["{res_headers}"] = TransToString(httpResp.Header)
statusCode := httpResp.StatusCode
if client.debug {
log.Printf("Invoke %s %s %d (%v)", ECSRequestMethod, requestURL, statusCode, t1.Sub(t0))
}
if span != nil {
ext.HTTPStatusCode.Set(span, uint16(httpResp.StatusCode))
}
defer httpResp.Body.Close()
body, err := ioutil.ReadAll(httpResp.Body)
fieldMap["{res_body}"] = string(body)
if err != nil {
return GetClientError(err)
}
if client.debug {
var prettyJSON bytes.Buffer
err = json.Indent(&prettyJSON, body, "", " ")
if err != nil {
log.Printf("Failed in json.Indent: %v\n", err)
}
log.Println(prettyJSON.String())
}
if statusCode >= 400 && statusCode <= 599 {
errorResponse := ErrorResponse{}
err = json.Unmarshal(body, &errorResponse)
if err != nil {
log.Printf("Failed in json.Unmarshal: %v\n", err)
}
ecsError := &Error{
ErrorResponse: errorResponse,
StatusCode: statusCode,
}
return ecsError
}
err = json.Unmarshal(body, response)
// log.Printf("%++v", response)
if err != nil {
return GetClientError(err)
}
return nil
}
// Invoke sends the raw HTTP request for ECS services
// 改进了一下上面那个方法,可以使用各种Http方法
// 2017.1.30 增加了一个path参数,用来拓展访问的地址
func (client *Client) InvokeByAnyMethod(method, action, path string, args interface{}, response interface{}) (err error) {
if err := client.ensureProperties(); err != nil {
return err
}
// log request
fieldMap := make(map[string]string)
initLogMsg(fieldMap)
defer func() {
client.printLog(fieldMap, err)
}()
// init endpoint
// if err := client.initEndpoint(); err != nil {
// return err
// }
request := Request{}
request.init(client.version, action, client.AccessKeyId, client.securityToken, client.regionID)
data := util.ConvertToQueryValues(request)
util.SetQueryValues(args, &data)
// Sign request
signature := util.CreateSignatureForRequest(method, &data, client.AccessKeySecret)
data.Add("Signature", signature)
// Generate the request URL
var (
httpReq *http.Request
)
if method == http.MethodGet {
requestURL := client.endpoint + path + "?" + data.Encode()
// fmt.Println(requestURL)
httpReq, err = http.NewRequest(method, requestURL, nil)
} else {
// fmt.Println(client.endpoint + path)
httpReq, err = http.NewRequest(method, client.endpoint+path, strings.NewReader(data.Encode()))
httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
if err != nil {
return GetClientError(err)
}
// TODO move to util and add build val flag
httpReq.Header.Set("X-SDK-Client", `AliyunGO/`+Version+client.businessInfo)
httpReq.Header.Set("User-Agent", httpReq.Header.Get("User-Agent")+" "+client.userAgent)
// Set tracer
var span opentracing.Span
if ok := opentracing.IsGlobalTracerRegistered(); ok && !client.disableTrace {
tracer := opentracing.GlobalTracer()
var rootCtx opentracing.SpanContext
if client.span != nil {
rootCtx = client.span.Context()
}
span = tracer.StartSpan(
"AliyunGO-"+request.Action,
opentracing.ChildOf(rootCtx),
opentracing.Tag{string(ext.Component), "AliyunGO"},
opentracing.Tag{"ActionName", request.Action})
defer span.Finish()
tracer.Inject(
span.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(httpReq.Header))
}
putMsgToMap(fieldMap, httpReq)
t0 := time.Now()
fieldMap["{start_time}"] = t0.Format("2006-01-02 15:04:05")
httpResp, err := client.httpClient.Do(httpReq)
t1 := time.Now()
fieldMap["{cost}"] = t1.Sub(t0).String()
if err != nil {
if span != nil {
ext.LogError(span, err)
}
return GetClientError(err)
}
fieldMap["{code}"] = strconv.Itoa(httpResp.StatusCode)
fieldMap["{res_headers}"] = TransToString(httpResp.Header)
statusCode := httpResp.StatusCode
if client.debug {
log.Printf("Invoke %s %s %d (%v) %v", ECSRequestMethod, client.endpoint, statusCode, t1.Sub(t0), data.Encode())
}
if span != nil {
ext.HTTPStatusCode.Set(span, uint16(httpResp.StatusCode))
}
defer httpResp.Body.Close()
body, err := ioutil.ReadAll(httpResp.Body)
fieldMap["{res_body}"] = string(body)
if err != nil {
return GetClientError(err)
}
if client.debug {
var prettyJSON bytes.Buffer
err = json.Indent(&prettyJSON, body, "", " ")
log.Println(prettyJSON.String())
}
if statusCode >= 400 && statusCode <= 599 {
errorResponse := ErrorResponse{}
err = json.Unmarshal(body, &errorResponse)
ecsError := &Error{
ErrorResponse: errorResponse,
StatusCode: statusCode,
}
return ecsError
}
err = json.Unmarshal(body, response)
// log.Printf("%++v", response)
if err != nil {
return GetClientError(err)
}
return nil
}
// GenerateClientToken generates the Client Token with random string
func (client *Client) GenerateClientToken() string {
return util.CreateRandomString()
}
func GetClientErrorFromString(str string) error {
return &Error{
ErrorResponse: ErrorResponse{
Code: "AliyunGoClientFailure",
Message: str,
},
StatusCode: -1,
}
}
func GetClientError(err error) error {
return GetClientErrorFromString(err.Error())
}
func GetCustomError(code, message string) error {
return &Error{
ErrorResponse: ErrorResponse{
Code: code,
Message: message,
},
StatusCode: 400,
}
}
func putMsgToMap(fieldMap map[string]string, request *http.Request) {
fieldMap["{host}"] = request.Host
fieldMap["{method}"] = request.Method
fieldMap["{uri}"] = request.URL.RequestURI()
fieldMap["{pid}"] = strconv.Itoa(os.Getpid())
fieldMap["{version}"] = strings.Split(request.Proto, "/")[1]
hostname, _ := os.Hostname()
fieldMap["{hostname}"] = hostname
fieldMap["{req_headers}"] = TransToString(request.Header)
fieldMap["{target}"] = request.URL.Path + request.URL.RawQuery
}