/
writer.go
135 lines (105 loc) · 2.64 KB
/
writer.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
package mns
import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"github.com/gogap/ali_mns"
"github.com/gogap/spirit"
)
const (
msnWriterURN = "urn:spirit-contrib:io:writer:mns"
)
var (
ErrMNSWriteMessageError = errors.New("ali-mns write message error")
)
var _ io.WriteCloser = new(MNSWriter)
type MNSWriterConfig struct {
URL string `json:"url"`
AccessKeyId string `json:"access_key_id"`
AccessKeySecret string `json:"access_key_secret"`
Queue string `json:"queue"`
DelaySeconds int `json:"delay_seconds"`
Priority int `json:"priority"`
ProxyAddress string `json:"proxy_address"`
}
type MNSWriter struct {
conf MNSWriterConfig
client ali_mns.MNSClient
}
func init() {
spirit.RegisterWriter(msnWriterURN, NewMNSWriter)
}
func NewMNSWriter(config spirit.Map) (w io.WriteCloser, err error) {
conf := MNSWriterConfig{}
if err = config.ToObject(&conf); err != nil {
return
}
if conf.Queue == "" {
err = ErrAliMNSQueueIsEmpty
return
}
if conf.URL == "" {
err = ErrAliURLIsEmpty
return
}
if conf.AccessKeyId == "" {
err = ErrAliAccessKeyIdIsEmpty
return
}
if conf.AccessKeySecret == "" {
err = ErrAliAccessKeySecretIsEmpty
return
}
if conf.Priority == 0 {
conf.Priority = 8
}
if conf.DelaySeconds > 604800 {
conf.DelaySeconds = 604800
}
if conf.DelaySeconds < 0 {
conf.DelaySeconds = 0
}
client := ali_mns.NewAliMNSClient(conf.URL, conf.AccessKeyId, conf.AccessKeySecret)
if conf.ProxyAddress != "" {
client.SetProxy(conf.ProxyAddress)
}
w = &MNSWriter{conf: conf, client: client}
return
}
func (p *MNSWriter) Write(data []byte) (n int, err error) {
resource := fmt.Sprintf("queues/%s/%s", p.conf.Queue, "messages")
reqData := ali_mns.MessageSendRequest{
MessageBody: ali_mns.Base64Bytes(data),
DelaySeconds: int64(p.conf.DelaySeconds),
Priority: int64(p.conf.Priority),
}
var resp *http.Response
if resp, err = p.client.Send(ali_mns.POST, nil, reqData, resource); err != nil {
return
}
if resp != nil {
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated &&
resp.StatusCode != http.StatusOK &&
resp.StatusCode != http.StatusNoContent {
err = ErrMNSWriteMessageError
if body, e := ioutil.ReadAll(resp.Body); e == nil {
spirit.Logger().WithField("actor", spirit.ActorWriter).
WithField("urn", msnWriterURN).
WithField("event", "write").
WithField("url", p.conf.URL).
WithField("queue", p.conf.Queue).
WithField("status_code", resp.StatusCode).
WithField("response", string(body)).
Debugln(err)
}
return
}
}
return
}
func (p *MNSWriter) Close() (err error) {
return
}