-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
115 lines (93 loc) · 2.05 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
package blackbox
import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"io/ioutil"
"net/http"
"net/url"
)
const (
StatusFailed = "FAILED"
StatusScheduled = "SCHEDULED"
StatusSent = "SENT"
StatusRejected = "REJECTED"
StatusSuccess = "SUCCESS"
StatusDescriptionOk = "OK"
)
type client struct {
config ClientConfig
httpClient *http.Client
}
type ClientConfig struct {
URL string
Key string
Signature string
}
func NewClient(cfg ClientConfig, httpClient *http.Client) Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
return &client{
config: cfg,
httpClient: httpClient,
}
}
type Client interface {
SendSMS(ctx context.Context, req *SendSMSRequest) (*SendSMSResponse, error)
}
func (c *client) SendSMS(ctx context.Context, msgReq *SendSMSRequest) (*SendSMSResponse, error) {
if msgReq == nil {
return nil, nil
}
msgXML, err := xml.Marshal(msgReq)
if err != nil {
return nil, err
}
vals := url.Values{}
vals.Add("messages", string(msgXML))
ret, err := c.postUrlEncoded(ctx, "/send_sms", vals)
if err != nil {
return nil, err
}
resp := &SendSMSResponse{}
err = json.Unmarshal(ret, resp)
if err != nil {
return nil, err
}
return resp, nil
}
func (c *client) postUrlEncoded(ctx context.Context, path string, vals url.Values) (ret []byte, err error) {
u, err := url.Parse(c.config.URL + path)
if err != nil {
return
}
vals.Add("api_key", c.config.Key)
vals.Add("api_signature", c.config.Signature)
vals.Add("api_format", "JSON")
req, err := http.NewRequest(http.MethodPost, u.String(), bytes.NewBuffer([]byte(vals.Encode())))
if err != nil {
return
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
if ctx != nil {
req = req.WithContext(ctx)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
ret, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if resp.StatusCode != http.StatusOK {
err = &Error{
HttpStatus: resp.StatusCode,
RawResponse: string(ret),
}
}
return ret, err
}