@@ -47,6 +47,14 @@ type Client struct {
47
47
DebugLog * log.Logger // Optional logger for debugging purposes
48
48
}
49
49
50
+ type contentType string
51
+
52
+ const (
53
+ contentTypeEmpty contentType = ""
54
+ contentTypeJSON contentType = "application/json"
55
+ contentTypeFormURLEncoded contentType = "application/x-www-form-urlencoded"
56
+ )
57
+
50
58
// New creates a new MessageBird client object.
51
59
func New (accessKey string ) * Client {
52
60
return & Client {
@@ -67,27 +75,24 @@ func (c *Client) Request(v interface{}, method, path string, data interface{}) e
67
75
return err
68
76
}
69
77
70
- var jsonEncoded []byte
71
- if data != nil {
72
- jsonEncoded , err = json .Marshal (data )
73
- if err != nil {
74
- return err
75
- }
78
+ body , contentType , err := prepareRequestBody (data )
79
+ if err != nil {
80
+ return err
76
81
}
77
82
78
- request , err := http .NewRequest (method , uri .String (), bytes .NewBuffer (jsonEncoded ))
83
+ request , err := http .NewRequest (method , uri .String (), bytes .NewBuffer (body ))
79
84
if err != nil {
80
85
return err
81
86
}
82
87
83
- request .Header .Set ("Content-Type" , "application/json" )
88
+ request .Header .Set ("Content-Type" , string ( contentType ) )
84
89
request .Header .Set ("Accept" , "application/json" )
85
90
request .Header .Set ("Authorization" , "AccessKey " + c .AccessKey )
86
91
request .Header .Set ("User-Agent" , "MessageBird/ApiClient/" + ClientVersion + " Go/" + runtime .Version ())
87
92
88
93
if c .DebugLog != nil {
89
94
if data != nil {
90
- c .DebugLog .Printf ("HTTP REQUEST: %s %s %s" , method , uri .String (), jsonEncoded )
95
+ c .DebugLog .Printf ("HTTP REQUEST: %s %s %s" , method , uri .String (), body )
91
96
} else {
92
97
c .DebugLog .Printf ("HTTP REQUEST: %s %s" , method , uri .String ())
93
98
}
@@ -136,3 +141,24 @@ func (c *Client) Request(v interface{}, method, path string, data interface{}) e
136
141
return errorResponse
137
142
}
138
143
}
144
+
145
+ // prepareRequestBody takes untyped data and attempts constructing a meaningful
146
+ // request body from it. It also returns the appropriate Content-Type.
147
+ func prepareRequestBody (data interface {}) ([]byte , contentType , error ) {
148
+ // Nil bodies are accepted by `net/http`, so this is not an error.
149
+ if data == nil {
150
+ return nil , contentTypeEmpty , nil
151
+ }
152
+
153
+ s , ok := data .(string )
154
+ if ok {
155
+ return []byte (s ), contentTypeFormURLEncoded , nil
156
+ }
157
+
158
+ b , err := json .Marshal (data )
159
+ if err != nil {
160
+ return nil , contentType ("" ), err
161
+ }
162
+
163
+ return b , contentTypeJSON , nil
164
+ }
0 commit comments