-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
90 lines (75 loc) · 1.63 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
package dribbble
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
)
// Client struct
type Client struct {
*Config
User *User
Projects *Projects
Shots *Shots
Jobs *Jobs
Likes *Likes
Attachments *Attachments
}
// New returns new instance of Dribbble client
func New(config *Config) *Client {
c := &Client{Config: config}
c.User = &User{c}
c.Projects = &Projects{c}
c.Shots = &Shots{c}
c.Jobs = &Jobs{c}
c.Likes = &Likes{c}
c.Attachments = &Attachments{c}
return c
}
func (c *Client) call(method string, path string, body interface{}) (io.ReadCloser, error) {
ep := "https://api.dribbble.com/v2" + path
u, err := url.Parse(ep)
if err != nil {
return nil, err
}
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+c.AccessToken)
req.Header.Set("Content-Type", "application/json")
r, _, err := c.do(req)
return r, err
}
func (c *Client) do(req *http.Request) (io.ReadCloser, int64, error) {
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, 0, err
}
if res.StatusCode < 400 {
return res.Body, res.ContentLength, err
}
defer res.Body.Close()
e := &Error{
StatusCode: res.StatusCode,
Message: res.Status,
}
ct := res.Header.Get("Content-Type")
if strings.Contains(ct, "text/html") {
return nil, 0, e
}
if err := json.NewDecoder(res.Body).Decode(e); err != nil {
return nil, 0, err
}
return nil, 0, e
}