File: client.go

package info (click to toggle)
golang-github-denverdino-aliyungo 0.0~git20180921.13fa8aa-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,824 kB
  • sloc: xml: 1,359; makefile: 3
file content (206 lines) | stat: -rwxr-xr-x 5,029 bytes parent folder | download | duplicates (3)
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
package ros

import (
	"bytes"
	"crypto/md5"
	"encoding/base64"
	"encoding/json"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"time"

	"fmt"

	"github.com/denverdino/aliyungo/common"
	"github.com/denverdino/aliyungo/util"
)

const (
	// ROSDefaultEndpoint is the default API endpoint of ROS services
	ROSDefaultEndpoint = "https://ros.aliyuncs.com"
	ROSAPIVersion      = "2015-09-01"
)

type Client struct {
	AccessKeyId     string
	AccessKeySecret string
	SecurityToken   string
	endpoint        string
	Version         string
	debug           bool
	userAgent       string
	httpClient      *http.Client
}

type Response struct {
	RequestId string `json:"request_id"`
}

// NewClient creates a new instance of ROS client
func NewClient(accessKeyId, accessKeySecret string) *Client {
	return &Client{
		AccessKeyId:     accessKeyId,
		AccessKeySecret: accessKeySecret,
		endpoint:        ROSDefaultEndpoint,
		Version:         ROSAPIVersion,
		httpClient:      &http.Client{},
	}
}

func NewROSClientWithSecurityToken(accessKeyId string, accessKeySecret string, securityToken string) *Client {
	return &Client{
		AccessKeyId:     accessKeyId,
		AccessKeySecret: accessKeySecret,
		SecurityToken:   securityToken,
		endpoint:        ROSDefaultEndpoint,
		Version:         ROSAPIVersion,
		httpClient:      &http.Client{},
	}
}

func NewClientForAussumeRole(accessKeyId, accessKeySecret, securityToken string) *Client {
	return &Client{
		AccessKeyId:     accessKeyId,
		AccessKeySecret: accessKeySecret,
		SecurityToken:   securityToken,
		endpoint:        ROSDefaultEndpoint,
		Version:         ROSAPIVersion,
		httpClient:      &http.Client{},
	}
}

// SetDebug sets debug mode to log the request/response message
func (client *Client) SetDebug(debug bool) {
	client.debug = debug
}

// SetUserAgent sets user agent to log the request/response message
func (client *Client) SetUserAgent(userAgent string) {
	client.userAgent = userAgent
}

func (client *Client) SetSecurityToken(securityToken string) {
	client.SecurityToken = securityToken
}

type Request struct {
	Method          string
	URL             string
	Version         string
	Region          common.Region
	Signature       string
	SignatureMethod string
	SignatureNonce  string
	Timestamp       util.ISO6801Time
	Body            []byte
}

// Invoke sends the raw HTTP request for ROS services
func (client *Client) Invoke(region common.Region, method string, path string, query url.Values, args interface{}, response interface{}) error {

	var reqBody []byte
	var err error
	var contentType string
	var contentMD5 string

	if args != nil {
		reqBody, err = json.Marshal(args)
		if err != nil {
			return err
		}
		contentType = "application/json"
		hasher := md5.New()
		hasher.Write(reqBody)
		contentMD5 = base64.StdEncoding.EncodeToString(hasher.Sum(nil))
	}

	requestURL := client.endpoint + path
	if query != nil && len(query) > 0 {
		requestURL = requestURL + "?" + util.Encode(query)
	}
	var bodyReader io.Reader
	if reqBody != nil {
		bodyReader = bytes.NewReader(reqBody)
	}
	httpReq, err := http.NewRequest(method, requestURL, bodyReader)
	if err != nil {
		return common.GetClientError(err)
	}

	if region != "" {
		httpReq.Header["x-acs-region-id"] = []string{string(region)}
	}

	if contentType != "" {
		httpReq.Header.Set("Content-Type", contentType)
	}
	if contentMD5 != "" {
		httpReq.Header.Set("Content-MD5", contentMD5)
	}
	// TODO move to util and add build val flag
	httpReq.Header.Set("Date", util.GetGMTime())
	httpReq.Header.Set("Accept", "application/json")
	//httpReq.Header.Set("x-acs-version", client.Version)

	httpReq.Header["x-acs-signature-version"] = []string{"1.0"}
	httpReq.Header["x-acs-signature-nonce"] = []string{util.CreateRandomString()}
	httpReq.Header["x-acs-signature-method"] = []string{"HMAC-SHA1"}

	if client.userAgent != "" {
		httpReq.Header.Set("User-Agent", client.userAgent)
	}

	if client.SecurityToken != "" {
		httpReq.Header["x-acs-security-token"] = []string{client.SecurityToken}
	}

	client.signRequest(httpReq)

	t0 := time.Now()
	httpResp, err := client.httpClient.Do(httpReq)
	t1 := time.Now()
	if err != nil {
		return common.GetClientError(err)
	}
	statusCode := httpResp.StatusCode

	if client.debug {
		fmt.Printf("Invoke %s %s %d (%v)", method, requestURL, statusCode, t1.Sub(t0))
	}

	defer httpResp.Body.Close()
	body, err := ioutil.ReadAll(httpResp.Body)

	if err != nil {
		return common.GetClientError(err)
	}

	if client.debug {
		var prettyJSON bytes.Buffer
		err = json.Indent(&prettyJSON, body, "", "    ")
		log.Println(string(prettyJSON.Bytes()))
	}

	if statusCode >= 400 && statusCode <= 599 {
		errorResponse := common.ErrorResponse{}
		err = json.Unmarshal(body, &errorResponse)
		cErr := &common.Error{
			ErrorResponse: errorResponse,
			StatusCode:    statusCode,
		}
		return cErr
	}

	if response != nil && len(body) > 0 {
		err = json.Unmarshal(body, response)
		//fmt.Printf("%++v", response)
		if err != nil {
			return common.GetClientError(err)
		}
	}

	return nil
}