-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient.go
81 lines (71 loc) · 1.78 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
package infobip
import (
"bytes"
"encoding/json"
"net/http"
)
const (
//SingleMessagePath for sending a single message
SingleMessagePath = "sms/1/text/single"
//AdvancedMessagePath for sending advanced messages
AdvancedMessagePath = "sms/1/text/advanced"
)
// HTTPInterface helps Infobip tests
type HTTPInterface interface {
Do(req *http.Request) (*http.Response, error)
}
// Client manages requests to Infobip
type Client struct {
BaseURL string
Username string
Password string
HTTPClient HTTPInterface
}
// ClientWithBasicAuth returns a pointer to infobip.Client with Infobip funcs
func ClientWithBasicAuth(username, password string) *Client {
return &Client{
BaseURL: "https://api.infobip.com/",
Username: username,
Password: password,
HTTPClient: &http.Client{},
}
}
// SingleMessage sends one message to one recipient
func (c Client) SingleMessage(m Message) (r Response, err error) {
if err = m.Validate(); err != nil {
return
}
b, err := json.Marshal(m)
if err != nil {
return
}
r, err = c.defaultRequest(b, SingleMessagePath)
return
}
// AdvancedMessage sends messages to the recipients
func (c Client) AdvancedMessage(m BulkMessage) (r Response, err error) {
if err = m.Validate(); err != nil {
return
}
b, err := json.Marshal(m)
if err != nil {
return
}
r, err = c.defaultRequest(b, AdvancedMessagePath)
return
}
func (c Client) defaultRequest(b []byte, path string) (r Response, err error) {
req, err := http.NewRequest(http.MethodPost, c.BaseURL+path, bytes.NewBuffer(b))
if err != nil {
return
}
req.SetBasicAuth(c.Username, c.Password)
req.Header.Add("Content-Type", "application/json")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&r)
return
}