This repository has been archived by the owner on Sep 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
client.go
83 lines (66 loc) · 1.87 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
package moneybird
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
// Client is the MoneyBird API consumer
type Client struct {
Token string
AdministrationID string
Logger *log.Logger
HTTPClient *http.Client
}
type envelope struct {
Contact *Contact `json:"contact,omitempty"`
Invoice *Invoice `json:"sales_invoice,omitempty"`
InvoiceSending *InvoiceSending `json:"sales_invoice_sending,omitempty"`
InvoicePayment *InvoicePayment `json:"payment,omitempty"`
InvoiceNote *InvoiceNote `json:"note,omitempty"`
LedgerAccount *LedgerAccount `json:"ledger_account,omitempty"`
}
func (c *Client) resourceURL(path string) string {
return "https://moneybird.com/api/v2/" + c.AdministrationID + "/" + path
}
func (c *Client) newRequest(method string, path string, data []byte) (*http.Request, error) {
var err error
url := c.resourceURL(path)
req, err := http.NewRequest(method, url, bytes.NewBuffer(data))
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+c.Token)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
return req, nil
}
func (c *Client) execute(method string, path string, env *envelope) (*Response, error) {
var data []byte
var err error
if env != nil {
data, err = json.Marshal(env)
if err != nil {
return nil, err
}
}
req, err := c.newRequest(method, path, data)
if err != nil {
return nil, err
}
if c.Logger != nil {
c.Logger.Printf("Moneybird: %s %s %s\n", req.Method, req.URL, req.Body)
}
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
if c.Logger != nil {
body, _ := ioutil.ReadAll(res.Body)
c.Logger.Printf("Moneybird: %s\n", res.Status)
c.Logger.Printf("Moneybird: %s\n", body)
res.Body = ioutil.NopCloser(bytes.NewBuffer(body))
}
return &Response{res}, nil
}