-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathclient.go
106 lines (86 loc) · 2.13 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 dropbox
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"strings"
)
// Client implements a Dropbox client. You may use the Files and Users
// clients directly if preferred, however Client exposes them both.
type Client struct {
*Config
Users *Users
Files *Files
Sharing *Sharing
}
// New client.
func New(config *Config) *Client {
c := &Client{Config: config}
c.Users = &Users{c}
c.Files = &Files{c}
c.Sharing = &Sharing{c}
return c
}
// call rpc style endpoint.
func (c *Client) call(path string, in interface{}) (io.ReadCloser, error) {
url := "https://api.dropboxapi.com/2" + path
body, err := json.Marshal(in)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", url, bytes.NewReader(body))
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
}
// download style endpoint.
func (c *Client) download(path string, in interface{}, r io.Reader) (io.ReadCloser, int64, error) {
url := "https://content.dropboxapi.com/2" + path
body, err := json.Marshal(in)
if err != nil {
return nil, 0, err
}
req, err := http.NewRequest("POST", url, r)
if err != nil {
return nil, 0, err
}
req.Header.Set("Authorization", "Bearer "+c.AccessToken)
req.Header.Set("Dropbox-API-Arg", string(body))
if r != nil {
req.Header.Set("Content-Type", "application/octet-stream")
}
return c.do(req)
}
// perform the request.
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{
Status: http.StatusText(res.StatusCode),
StatusCode: res.StatusCode,
}
kind := res.Header.Get("Content-Type")
if strings.Contains(kind, "text/plain") {
if b, err := ioutil.ReadAll(res.Body); err == nil {
e.Summary = string(b)
return nil, 0, e
}
return nil, 0, err
}
if err := json.NewDecoder(res.Body).Decode(e); err != nil {
return nil, 0, err
}
return nil, 0, e
}