forked from gogap/ali_mns
-
Notifications
You must be signed in to change notification settings - Fork 10
/
client.go
214 lines (176 loc) · 5.65 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
package ali_mns
import (
"crypto/md5"
"encoding/base64"
"encoding/xml"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/gogap/errors"
"github.com/mreiferson/go-httpclient"
)
const (
version = "2015-06-06"
)
const (
DefaultTimeout int64 = 35
)
type Method string
var (
errMapping map[string]errors.ErrCodeTemplate
)
func init() {
initMNSErrors()
}
const (
GET Method = "GET"
PUT = "PUT"
POST = "POST"
DELETE = "DELETE"
)
type MNSClient interface {
Send(method Method, headers map[string]string, message interface{}, resource string) (resp *http.Response, err error)
SetProxy(url string)
}
type AliMNSClient struct {
Timeout int64
url string
credential Credential
accessKeyId string
clientLocker sync.Mutex
client *http.Client
proxyURL string
}
func NewAliMNSClient(url, accessKeyId, accessKeySecret string) MNSClient {
if url == "" {
panic("ali-mns: message queue url is empty")
}
credential := NewAliMNSCredential(accessKeySecret)
aliMNSClient := new(AliMNSClient)
aliMNSClient.credential = credential
aliMNSClient.accessKeyId = accessKeyId
aliMNSClient.url = url
timeoutInt := DefaultTimeout
if aliMNSClient.Timeout > 0 {
timeoutInt = aliMNSClient.Timeout
}
timeout := time.Second * time.Duration(timeoutInt)
transport := &httpclient.Transport{
Proxy: aliMNSClient.proxy,
ConnectTimeout: time.Second * 3,
RequestTimeout: timeout,
ResponseHeaderTimeout: timeout + time.Second,
}
aliMNSClient.client = &http.Client{Transport: transport}
return aliMNSClient
}
func (p *AliMNSClient) SetProxy(url string) {
p.proxyURL = url
}
func (p *AliMNSClient) proxy(req *http.Request) (*url.URL, error) {
if p.proxyURL != "" {
return url.Parse(p.proxyURL)
}
return nil, nil
}
func (p *AliMNSClient) authorization(method Method, headers map[string]string, resource string) (authHeader string, err error) {
if signature, e := p.credential.Signature(method, headers, resource); e != nil {
return "", e
} else {
authHeader = fmt.Sprintf("MNS %s:%s", p.accessKeyId, signature)
}
return
}
func (p *AliMNSClient) Send(method Method, headers map[string]string, message interface{}, resource string) (resp *http.Response, err error) {
var xmlContent []byte
if message == nil {
xmlContent = []byte{}
} else {
switch m := message.(type) {
case []byte:
{
xmlContent = m
}
default:
if bXml, e := xml.Marshal(message); e != nil {
err = ERR_MARSHAL_MESSAGE_FAILED.New(errors.Params{"err": e})
return
} else {
xmlContent = bXml
}
}
}
xmlMD5 := md5.Sum(xmlContent)
strMd5 := fmt.Sprintf("%x", xmlMD5)
if headers == nil {
headers = make(map[string]string)
}
headers[MQ_VERSION] = version
headers[CONTENT_TYPE] = "application/xml"
headers[CONTENT_MD5] = base64.StdEncoding.EncodeToString([]byte(strMd5))
headers[DATE] = time.Now().UTC().Format(http.TimeFormat)
if authHeader, e := p.authorization(method, headers, fmt.Sprintf("/%s", resource)); e != nil {
err = ERR_GENERAL_AUTH_HEADER_FAILED.New(errors.Params{"err": e})
return
} else {
headers[AUTHORIZATION] = authHeader
}
url := p.url + "/" + resource
postBodyReader := strings.NewReader(string(xmlContent))
// 莫名的lock 加这个是为了啥 想不通。。 推拉模式 加lock 这是直接限流请求了
// p.clientLocker.Lock()
// defer p.clientLocker.Unlock()
var req *http.Request
if req, err = http.NewRequest(string(method), url, postBodyReader); err != nil {
err = ERR_CREATE_NEW_REQUEST_FAILED.New(errors.Params{"err": err})
return
}
for header, value := range headers {
req.Header.Add(header, value)
}
if resp, err = p.client.Do(req); err != nil {
err = ERR_SEND_REQUEST_FAILED.New(errors.Params{"err": err})
return
}
return
}
func initMNSErrors() {
errMapping = map[string]errors.ErrCodeTemplate{
"AccessDenied": ERR_MNS_ACCESS_DENIED,
"InvalidAccessKeyId": ERR_MNS_INVALID_ACCESS_KEY_ID,
"InternalError": ERR_MNS_INTERNAL_ERROR,
"InvalidAuthorizationHeader": ERR_MNS_INVALID_AUTHORIZATION_HEADER,
"InvalidDateHeader": ERR_MNS_INVALID_DATE_HEADER,
"InvalidArgument": ERR_MNS_INVALID_ARGUMENT,
"InvalidDegist": ERR_MNS_INVALID_DEGIST,
"InvalidRequestURL": ERR_MNS_INVALID_REQUEST_URL,
"InvalidQueryString": ERR_MNS_INVALID_QUERY_STRING,
"MalformedXML": ERR_MNS_MALFORMED_XML,
"MissingAuthorizationHeader": ERR_MNS_MISSING_AUTHORIZATION_HEADER,
"MissingDateHeader": ERR_MNS_MISSING_DATE_HEADER,
"MissingVersionHeader": ERR_MNS_MISSING_VERSION_HEADER,
"MissingReceiptHandle": ERR_MNS_MISSING_RECEIPT_HANDLE,
"MissingVisibilityTimeout": ERR_MNS_MISSING_VISIBILITY_TIMEOUT,
"MessageNotExist": ERR_MNS_MESSAGE_NOT_EXIST,
"QueueAlreadyExist": ERR_MNS_QUEUE_ALREADY_EXIST,
"QueueDeletedRecently": ERR_MNS_QUEUE_DELETED_RECENTLY,
"InvalidQueueName": ERR_MNS_INVALID_QUEUE_NAME,
"QueueNameLengthError": ERR_MNS_QUEUE_NAME_LENGTH_ERROR,
"QueueNotExist": ERR_MNS_QUEUE_NOT_EXIST,
"ReceiptHandleError": ERR_MNS_RECEIPT_HANDLE_ERROR,
"SignatureDoesNotMatch": ERR_MNS_SIGNATURE_DOES_NOT_MATCH,
"TimeExpired": ERR_MNS_TIME_EXPIRED,
"QpsLimitExceeded": ERR_MNS_QPS_LIMIT_EXCEEDED,
}
}
func ParseError(resp ErrorMessageResponse, resource string) (err error) {
if errCodeTemplate, exist := errMapping[resp.Code]; exist {
err = errCodeTemplate.New(errors.Params{"resp": resp, "resource": resource})
} else {
err = ERR_MNS_UNKNOWN_CODE.New(errors.Params{"resp": resp, "resource": resource})
}
return
}