-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
120 lines (99 loc) · 2.37 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
// Package xesende is a client for the Esendex REST API.
package xesende
import (
"bytes"
"encoding/xml"
"fmt"
"net/http"
"net/url"
)
const (
defaultBaseURL = "https://api.esendex.com/"
defaultUserAgent = "xesende/golang"
)
// Client is the entry point for accessing the Esendex REST API.
type Client struct {
client *http.Client
user string
pass string
BaseURL *url.URL
UserAgent string
}
// New returns a new API client that authenticates with the credentials provided.
func New(user, pass string) *Client {
baseURL, _ := url.Parse(defaultBaseURL)
return &Client{
client: http.DefaultClient,
user: user,
pass: pass,
BaseURL: baseURL,
UserAgent: defaultUserAgent,
}
}
func (c *Client) newRequest(method, path string, body interface{}) (*http.Request, error) {
reqURL, err := c.BaseURL.Parse(path)
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
if body != nil {
if err := xml.NewEncoder(buf).Encode(body); err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, reqURL.String(), buf)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/xml")
req.Header.Add("User-Agent", c.UserAgent)
req.SetBasicAuth(c.user, c.pass)
return req, nil
}
func (c *Client) do(req *http.Request, v interface{}) (*http.Response, error) {
resp, err := c.client.Do(req)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, ClientError{
Method: req.Method,
Path: req.URL.Path,
Code: resp.StatusCode,
}
}
if err != nil {
return resp, err
}
defer func() {
if rerr := resp.Body.Close(); err == nil {
err = rerr
}
}()
if v != nil {
if err := xml.NewDecoder(resp.Body).Decode(v); err != nil {
return resp, err
}
}
return resp, err
}
// AccountClient is a client scoped to a specific account reference.
type AccountClient struct {
*Client
reference string
}
// Account creates a client that can make requests scoped to a specific account
// reference.
func (c *Client) Account(reference string) *AccountClient {
return &AccountClient{
Client: c,
reference: reference,
}
}
// ClientError is the type of error returned when an unexpected (non-200 range)
// response is returned by the API.
type ClientError struct {
Method string
Path string
Code int
}
func (e ClientError) Error() string {
return fmt.Sprintf("%s %s: %d", e.Method, e.Path, e.Code)
}