This repository has been archived by the owner on Jul 13, 2022. It is now read-only.
forked from MDrollette/taxjar-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
106 lines (86 loc) · 2.2 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
package taxjar
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/google/go-querystring/query"
)
type Client struct {
*http.Client
baseUri string
token string
Debug bool
Categories CategoryService
Rates RateService
Taxes TaxService
}
func NewClient(token string) *Client {
c := &Client{Client: &http.Client{}, token: token, baseUri: "https://api.taxjar.com/v2", Debug: false}
c.Setup()
return c
}
func (c Client) Get(url string, queryParams interface{}) ([]byte, error) {
req, _ := http.NewRequest("GET", c.baseUri+url, nil)
req.Header.Add("Authorization", "Bearer "+c.token)
req.Header.Add("Accept", "application/json")
addQueryParams(req, queryParams)
if c.Debug {
fmt.Printf("%s %s\n", req.Method, req.URL)
}
resp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("error: %s", resp.StatusCode)
}
return data, err
}
func (c Client) Post(url string, params interface{}) ([]byte, error) {
buffer := bytes.NewBuffer([]byte{})
if err := json.NewEncoder(buffer).Encode(params); err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.baseUri+url, buffer)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+c.token)
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
if c.Debug {
fmt.Printf("%s %s %s\n", req.Method, req.URL, buffer)
}
resp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if c.Debug {
fmt.Printf("Response: %s\n", data)
}
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("error: %d %s", resp.StatusCode, data)
}
return data, err
}
func (c *Client) Setup() {
c.Categories = CategoryService{Repository: CategoryApi{client: c}}
c.Rates = RateService{Repository: RateApi{client: c}}
c.Taxes = TaxService{Repository: TaxApi{client: c}}
}
func addQueryParams(req *http.Request, params interface{}) {
v, _ := query.Values(params)
req.URL.RawQuery = v.Encode()
}