Skip to content

Commit f5e21e5

Browse files
author
Dirk Hoekstra
committed
Send JSON data to API
1 parent 1f8d7d0 commit f5e21e5

File tree

6 files changed

+196
-149
lines changed

6 files changed

+196
-149
lines changed

client.go

Lines changed: 51 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,15 @@
1010
package messagebird
1111

1212
import (
13+
"bytes"
1314
"encoding/json"
1415
"errors"
16+
"fmt"
1517
"io/ioutil"
1618
"log"
1719
"net/http"
1820
"net/url"
1921
"runtime"
20-
"strings"
2122
)
2223

2324
const (
@@ -49,41 +50,46 @@ func New(AccessKey string) *Client {
4950
return &Client{AccessKey: AccessKey, HTTPClient: &http.Client{}}
5051
}
5152

52-
func (c *Client) request(v interface{}, path string, params *url.Values) error {
53+
func (c *Client) request(v interface{}, path string, data interface{}) error {
5354
uri, err := url.Parse(Endpoint + "/" + path)
5455
if err != nil {
5556
return err
5657
}
5758

58-
var request *http.Request
59-
if params != nil {
60-
body := params.Encode()
61-
if request, err = http.NewRequest("POST", uri.String(), strings.NewReader(body)); err != nil {
59+
method := "GET"
60+
var jsonEncoded []byte
61+
if data != nil {
62+
jsonEncoded, err = json.Marshal(data)
63+
method = "POST"
64+
if err != nil {
6265
return err
6366
}
67+
}
6468

65-
if c.DebugLog != nil {
66-
if unescapedBody, queryError := url.QueryUnescape(body); queryError == nil {
67-
log.Printf("HTTP REQUEST: POST %s %s", uri.String(), unescapedBody)
68-
} else {
69-
log.Printf("HTTP REQUEST: POST %s %s", uri.String(), body)
70-
}
71-
}
69+
request, err := http.NewRequest(method, uri.String(), bytes.NewBuffer(jsonEncoded))
70+
if err != nil {
71+
return err
72+
}
7273

73-
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
74-
} else {
75-
if request, err = http.NewRequest("GET", uri.String(), nil); err != nil {
76-
return err
77-
}
74+
request.Header.Set("Content-Type", "application/json")
75+
request.Header.Set("Accept", "application/json")
76+
request.Header.Set("Authorization", "AccessKey "+c.AccessKey)
77+
request.Header.Add("User-Agent", "MessageBird/ApiClient/"+ClientVersion+" Go/"+runtime.Version())
7878

79-
if c.DebugLog != nil {
80-
log.Printf("HTTP REQUEST: GET %s", uri.String())
79+
if c.DebugLog != nil {
80+
if data != nil {
81+
log.Printf("HTTP REQUEST: %s %s %s", method, uri.String(), jsonEncoded)
82+
} else {
83+
log.Printf("HTTP REQUEST: %s %s", method, uri.String())
8184
}
8285
}
8386

84-
request.Header.Add("Accept", "application/json")
85-
request.Header.Add("Authorization", "AccessKey "+c.AccessKey)
86-
request.Header.Add("User-Agent", "MessageBird/ApiClient/"+ClientVersion+" Go/"+runtime.Version())
87+
// TODO remove this
88+
if data != nil {
89+
fmt.Printf("HTTP REQUEST: %s %s %s\n", method, uri.String(), jsonEncoded)
90+
} else {
91+
fmt.Printf("HTTP REQUEST: %s %s\n", method, uri.String())
92+
}
8793

8894
response, err := c.HTTPClient.Do(request)
8995
if err != nil {
@@ -101,6 +107,9 @@ func (c *Client) request(v interface{}, path string, params *url.Values) error {
101107
log.Printf("HTTP RESPONSE: %s", string(responseBody))
102108
}
103109

110+
// TODO remove this
111+
fmt.Printf("HTTP RESPONSE: %s\n", string(responseBody))
112+
104113
// Status code 500 is a server error and means nothing can be done at this
105114
// point.
106115
if response.StatusCode == 500 {
@@ -152,14 +161,14 @@ func (c *Client) HLR(id string) (*HLR, error) {
152161
}
153162

154163
// NewHLR retrieves the information of an existing HLR.
155-
func (c *Client) NewHLR(msisdn, reference string) (*HLR, error) {
156-
params := &url.Values{
157-
"msisdn": {msisdn},
158-
"reference": {reference},
164+
func (c *Client) NewHLR(msisdn string, reference string) (*HLR, error) {
165+
requestData, err := requestDataForHLR(msisdn, reference)
166+
if err != nil {
167+
return nil, err
159168
}
160169

161170
hlr := &HLR{}
162-
if err := c.request(hlr, "hlr", params); err != nil {
171+
if err := c.request(hlr, "hlr", requestData); err != nil {
163172
if err == ErrResponse {
164173
return hlr, err
165174
}
@@ -186,17 +195,13 @@ func (c *Client) Message(id string) (*Message, error) {
186195

187196
// NewMessage creates a new message for one or more recipients.
188197
func (c *Client) NewMessage(originator string, recipients []string, body string, msgParams *MessageParams) (*Message, error) {
189-
params, err := paramsForMessage(msgParams)
198+
requestData, err := requestDataForMessage(originator, recipients, body, msgParams)
190199
if err != nil {
191200
return nil, err
192201
}
193202

194-
params.Set("originator", originator)
195-
params.Set("body", body)
196-
params.Set("recipients", strings.Join(recipients, ","))
197-
198203
message := &Message{}
199-
if err := c.request(message, "messages", params); err != nil {
204+
if err := c.request(message, "messages", requestData); err != nil {
200205
if err == ErrResponse {
201206
return message, err
202207
}
@@ -223,12 +228,13 @@ func (c *Client) VoiceMessage(id string) (*VoiceMessage, error) {
223228

224229
// NewVoiceMessage creates a new voice message for one or more recipients.
225230
func (c *Client) NewVoiceMessage(recipients []string, body string, params *VoiceMessageParams) (*VoiceMessage, error) {
226-
urlParams := paramsForVoiceMessage(params)
227-
urlParams.Set("body", body)
228-
urlParams.Set("recipients", strings.Join(recipients, ","))
231+
requestData, err := requestDataForVoiceMessage(recipients, body, params)
232+
if err != nil {
233+
return nil, err
234+
}
229235

230236
message := &VoiceMessage{}
231-
if err := c.request(message, "voicemessages", urlParams); err != nil {
237+
if err := c.request(message, "voicemessages", requestData); err != nil {
232238
if err == ErrResponse {
233239
return message, err
234240
}
@@ -241,11 +247,13 @@ func (c *Client) NewVoiceMessage(recipients []string, body string, params *Voice
241247

242248
// NewVerify generates a new One-Time-Password for one recipient.
243249
func (c *Client) NewVerify(recipient string, params *VerifyParams) (*Verify, error) {
244-
urlParams := paramsForVerify(params)
245-
urlParams.Set("recipient", recipient)
250+
requestData, err := requestDataForVerify(recipient, params)
251+
if err != nil {
252+
return nil, err
253+
}
246254

247255
verify := &Verify{}
248-
if err := c.request(verify, "verify", urlParams); err != nil {
256+
if err := c.request(verify, "verify", requestData); err != nil {
249257
if err == ErrResponse {
250258
return verify, err
251259
}
@@ -294,11 +302,11 @@ func (c *Client) Lookup(phoneNumber string, params *LookupParams) (*Lookup, erro
294302

295303
// NewLookupHLR creates a new HLR lookup for the specified number.
296304
func (c *Client) NewLookupHLR(phoneNumber string, params *LookupParams) (*HLR, error) {
297-
urlParams := paramsForLookup(params)
305+
requestData := requestDataForLookup(params)
298306
path := "lookup/" + phoneNumber + "/hlr"
299307

300308
hlr := &HLR{}
301-
if err := c.request(hlr, path, urlParams); err != nil {
309+
if err := c.request(hlr, path, requestData); err != nil {
302310
if err == ErrResponse {
303311
return hlr, err
304312
}

hlr.go

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package messagebird
22

3-
import "time"
3+
import (
4+
"errors"
5+
"time"
6+
)
47

58
// HLR stands for Home Location Register.
69
// Contains information about the subscribers identity, telephone number, the associated services and general information about the location of the subscriber
@@ -16,3 +19,24 @@ type HLR struct {
1619
StatusDatetime *time.Time
1720
Errors []Error
1821
}
22+
23+
type hlrRequest struct {
24+
MSISDN string `json:"msisdn"`
25+
Reference string `json:"reference"`
26+
}
27+
28+
func requestDataForHLR(msisdn string, reference string) (*hlrRequest, error) {
29+
request := &hlrRequest{}
30+
31+
if msisdn == "" {
32+
return nil, errors.New("msisdn is required")
33+
}
34+
if reference == "" {
35+
return nil, errors.New("reference is required")
36+
}
37+
38+
request.MSISDN = msisdn
39+
request.Reference = reference
40+
41+
return request, nil
42+
}

lookup.go

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package messagebird
22

3-
import "net/url"
3+
import (
4+
"net/url"
5+
)
46

57
// Formats represents phone number in multiple formats.
68
type Formats struct {
@@ -27,6 +29,24 @@ type LookupParams struct {
2729
Reference string
2830
}
2931

32+
type lookupRequest struct {
33+
CountryCode string `json:"countryCode,omitempty"`
34+
Reference string `json:"reference,omitempty"`
35+
}
36+
37+
func requestDataForLookup(params *LookupParams) *lookupRequest {
38+
request := &lookupRequest{}
39+
40+
if params == nil {
41+
return request
42+
}
43+
44+
request.CountryCode = params.CountryCode
45+
request.Reference = params.Reference
46+
47+
return request
48+
}
49+
3050
func paramsForLookup(params *LookupParams) *url.Values {
3151
urlParams := &url.Values{}
3252

message.go

Lines changed: 38 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@ package messagebird
22

33
import (
44
"errors"
5-
"net/url"
6-
"strconv"
75
"time"
86
)
97

@@ -42,47 +40,52 @@ type MessageParams struct {
4240
ScheduledDatetime time.Time
4341
}
4442

45-
// paramsForMessage converts the specified MessageParams struct to a
46-
// url.Values pointer and returns it.
47-
func paramsForMessage(params *MessageParams) (*url.Values, error) {
48-
urlParams := &url.Values{}
43+
type messageRequest struct {
44+
Originator string `json:"originator"`
45+
Body string `json:"body"`
46+
Recipients []string `json:"recipients"`
47+
Type string `json:"type,omitempty"`
48+
Reference string `json:"reference,omitempty"`
49+
Validity int `json:"validity,omitempty"`
50+
Gateway int `json:"gateway,omitempty"`
51+
TypeDetails TypeDetails `json:"typeDetails,omitempty"`
52+
DataCoding string `json:"dataCoding,omitempty"`
53+
MClass int `json:"mclass,omitempty"`
54+
ScheduledDatetime string `json:"scheduledDatetime,omitempty"`
55+
}
4956

50-
if params == nil {
51-
return urlParams, nil
52-
}
57+
func requestDataForMessage(originator string, recipients []string, body string, params *MessageParams) (*messageRequest, error) {
58+
request := &messageRequest{}
5359

54-
if params.Type != "" {
55-
urlParams.Set("type", params.Type)
56-
if params.Type == "flash" {
57-
urlParams.Set("mclass", "0")
58-
}
60+
if originator == "" {
61+
return nil, errors.New("originator is required")
5962
}
60-
if params.Reference != "" {
61-
urlParams.Set("reference", params.Reference)
63+
if len(recipients) == 0 {
64+
return nil, errors.New("at least 1 recipient is required")
6265
}
63-
if params.Validity != 0 {
64-
urlParams.Set("validity", strconv.Itoa(params.Validity))
65-
}
66-
if params.Gateway != 0 {
67-
urlParams.Set("gateway", strconv.Itoa(params.Gateway))
66+
if body == "" {
67+
return nil, errors.New("body is required")
6868
}
69+
request.Originator = originator
70+
request.Recipients = recipients
71+
request.Body = body
6972

70-
for k, v := range params.TypeDetails {
71-
if vs, ok := v.(string); ok {
72-
urlParams.Set("typeDetails["+k+"]", vs)
73-
} else if vi, ok := v.(int); ok {
74-
urlParams.Set("typeDetails["+k+"]", strconv.Itoa(vi))
75-
} else {
76-
return nil, errors.New("Unknown type for typeDetails value")
77-
}
73+
if params == nil {
74+
return request, nil
7875
}
7976

80-
if params.DataCoding != "" {
81-
urlParams.Set("datacoding", params.DataCoding)
82-
}
83-
if params.ScheduledDatetime.Unix() > 0 {
84-
urlParams.Set("scheduledDatetime", params.ScheduledDatetime.Format(time.RFC3339))
77+
request.Type = params.Type
78+
if request.Type == "flash" {
79+
request.MClass = 0
80+
} else {
81+
request.MClass = 1
8582
}
83+
request.Reference = params.Reference
84+
request.Validity = params.Validity
85+
request.Gateway = params.Gateway
86+
request.TypeDetails = params.TypeDetails
87+
request.DataCoding = params.DataCoding
88+
request.ScheduledDatetime = params.ScheduledDatetime.Format(time.RFC3339)
8689

87-
return urlParams, nil
90+
return request, nil
8891
}

0 commit comments

Comments
 (0)