-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
323 lines (263 loc) · 7.36 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package avida
import (
"bytes"
"context"
"encoding/xml"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"github.com/tim-online/go-avida/soap"
)
const (
libraryVersion = "0.0.1"
userAgent = "go-mews/" + libraryVersion
// mediaType = "application/soap+xml"
mediaType = "text/xml"
charset = "utf-8"
// xmlns = "https://test-srv.avidafinance.com/InvoiceInformation1/InvoiceService.svc?wsdl=wsdl0"
)
var (
BaseURL = url.URL{
Scheme: "https",
Host: "srv.avidafinance.com",
Path: "/InvoiceInformation1/InvoiceService.svc",
}
BaseURLTest = url.URL{
Scheme: "https",
Host: "test-srv.avidafinance.com",
Path: "/InvoiceInformation1/InvoiceService.svc/basic",
}
)
// NewClient returns a new MEWS API client
func NewClient(httpClient *http.Client, username string, password string) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
c := &Client{
http: httpClient,
}
c.SetUsername(username)
c.SetPassword(password)
c.SetBaseURL(BaseURL)
c.SetUserAgent(userAgent)
c.SetMediaType(mediaType)
c.SetCharset(charset)
// Services
c.Invoice = NewInvoiceService(c)
return c
}
// Client manages communication with MEWS API
type Client struct {
// HTTP client used to communicate with the API.
http *http.Client
// Credentials
username string
password string
debug bool
baseURL url.URL
// User agent for client
userAgent string
mediaType string
charset string
// Optional function called after every successful request made to the DO APIs
onRequestCompleted RequestCompletionCallback
// Services used for communicating with the API
Invoice *InvoiceService
}
// RequestCompletionCallback defines the type of the request callback function
type RequestCompletionCallback func(*http.Request, *http.Response)
func (c *Client) SetDebug(debug bool) {
c.debug = debug
}
func (c *Client) SetBaseURL(baseURL url.URL) {
c.baseURL = baseURL
}
func (c *Client) SetUsername(username string) {
c.username = username
}
func (c *Client) SetPassword(password string) {
c.password = password
}
func (c *Client) SetMediaType(mediaType string) {
c.mediaType = mediaType
}
func (c *Client) MediaType() string {
return mediaType
}
func (c *Client) SetCharset(charset string) {
c.charset = charset
}
func (c *Client) Charset() string {
return charset
}
func (c *Client) SetUserAgent(userAgent string) {
c.userAgent = userAgent
}
func (c *Client) UserAgent() string {
return userAgent
}
func (c *Client) Auth() Auth {
return Auth{
Username: c.username,
Password: c.password,
}
}
func (c *Client) NewRequest(ctx context.Context, soapRequest *soap.Request) (*http.Request, error) {
// convert body struct to xml
buf := new(bytes.Buffer)
if soapRequest != nil {
// Add xml declaration
buf.Write([]byte(xml.Header))
err := xml.NewEncoder(buf).Encode(soapRequest.Envelope())
if err != nil {
return nil, err
}
}
// create new http request
req, err := http.NewRequest("POST", c.baseURL.String(), buf)
if err != nil {
return nil, err
}
// optionally pass along context
if ctx != nil {
req = req.WithContext(ctx)
}
req.Header.Add("Content-Type", fmt.Sprintf("%s; charset=%s", c.MediaType(), c.Charset()))
req.Header.Add("Accept", c.MediaType())
req.Header.Add("User-Agent", c.UserAgent())
req.Header.Add("SOAPAction", soapRequest.Action().String())
return req, nil
}
// Do sends an API request and returns the API response. The API response is XML decoded and stored in the value
// pointed to by v, or returned as an error if an API error has occurred. If v implements the io.Writer interface,
// the raw response will be written to v, without attempting to decode it.
func (c *Client) Do(req *http.Request, soapResponse *soap.Response) (*http.Response, error) {
if c.debug == true {
dump, _ := httputil.DumpRequestOut(req, true)
log.Println(string(dump))
}
httpResp, err := c.http.Do(req)
if err != nil {
return nil, err
}
if c.onRequestCompleted != nil {
c.onRequestCompleted(req, httpResp)
}
// close body io.Reader
defer func() {
if rerr := httpResp.Body.Close(); err == nil {
err = rerr
}
}()
if c.debug == true {
dump, _ := httputil.DumpResponse(httpResp, true)
log.Println(string(dump))
}
// check if the response isn't an error
err = CheckResponse(httpResp)
if err != nil {
return httpResp, err
}
// check the provided interface parameter
if httpResp == nil {
return httpResp, err
}
// interface implements io.Writer: write Body to it
// if w, ok := response.Envelope.(io.Writer); ok {
// _, err := io.Copy(w, httpResp.Body)
// return httpResp, err
// }
// try to decode body into interface parameter
err = xml.NewDecoder(httpResp.Body).Decode(soapResponse.Envelope())
if err != nil {
errorResponse := &ErrorResponse{Response: httpResp}
errorResponse.Message = err.Error()
return httpResp, errorResponse
}
return httpResp, nil
}
// CheckResponse checks the API response for errors, and returns them if
// present. A response is considered an error if it has a status code outside
// the 200 range. API error responses are expected to have either no response
// body, or a XML response body that maps to ErrorResponse. Any other response
// body will be silently ignored.
func CheckResponse(r *http.Response) error {
errorResponse := &ErrorResponse{Response: r}
err := checkContentType(r)
if err != nil {
errorResponse.Message = err.Error()
}
if r.Header.Get("Content-Length") == "0" {
errorResponse.Message = r.Status
return errorResponse
}
if c := r.StatusCode; c >= 200 && c <= 299 {
return nil
}
// read data and copy it back
data, err := ioutil.ReadAll(r.Body)
r.Body = nopCloser{bytes.NewReader(data)}
if err != nil {
return errorResponse
}
if len(data) == 0 {
return errorResponse
}
// convert xml to struct
err = xml.Unmarshal(data, errorResponse)
if err != nil {
errorResponse.Message = fmt.Sprintf("Malformed xml response")
return errorResponse
}
if errorResponse.Message != "" {
return errorResponse
}
return nil
}
// An ErrorResponse reports the error caused by an API request
// <?xml version="1.0" encoding="UTF-8"?>
// <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
// <SOAP-ENV:Body>
// <SOAP-ENV:Fault>
// <faultcode>Sender</faultcode>
// <faultstring>Invalid XML</faultstring>
// </SOAP-ENV:Fault>
// </SOAP-ENV:Body>
// </SOAP-ENV:Envelope>type ErrorResponse struct {
type ErrorResponse struct {
// HTTP response that caused this error
Response *http.Response
// Fault code
Code string `xml:"Body>Fault>faultcode"`
// Fault message
Message string `xml:"Body>Fault>faultstring"`
// Reason
Reason string `xml:"Body>Fault>Reason>Text"`
}
func (r *ErrorResponse) Error() string {
return fmt.Sprintf("%v %v: %d (%v %v)",
r.Response.Request.Method, r.Response.Request.URL, r.Response.StatusCode, r.Message, r.Reason)
}
func checkContentType(response *http.Response) error {
// check content-type (application/soap+xml; charset=utf-8)
header := response.Header.Get("Content-Type")
contentType := strings.Split(header, ";")[0]
if contentType != "text/xml" {
return fmt.Errorf("Expected Content-Type \"text/xml\", got \"%s\"", contentType)
}
return nil
}
type Auth struct {
Username string `xml:"Username"`
Password string `xml:"Password"`
}
func (a Auth) Empty() bool {
if a.Username == "" && a.Password == "" {
return true
}
return false
}