-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclient.go
191 lines (161 loc) · 3.82 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package crowi
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"os"
"path"
"runtime"
"strings"
"golang.org/x/net/context"
"golang.org/x/net/context/ctxhttp"
)
const version = "0.1"
var userAgent = fmt.Sprintf("CrowiGoClient/%s (%s)", version, runtime.Version())
type Client struct {
http.Client
config Config
common service // Reuse a single struct instead of allocating one for each service on the heap.
Pages *PagesService
Attachments *AttachmentsService
}
type service struct {
client *Client
}
type ListOptions struct {
Pagenation bool
}
type Config struct {
URL string
Token string
InsecureSkipVerify bool
}
func NewClient(cfg Config) (*Client, error) {
if len(cfg.URL) == 0 {
return nil, errors.New("missing api url")
}
if len(cfg.Token) == 0 {
return nil, errors.New("missing token")
}
client := *http.DefaultClient
if cfg.InsecureSkipVerify {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = http.Client{Transport: tr}
}
c := &Client{
Client: client,
config: cfg,
}
c.common.client = c
c.Pages = (*PagesService)(&c.common)
c.Attachments = (*AttachmentsService)(&c.common)
return c, nil
}
func (c *Client) newRequest(ctx context.Context, method string, uri string, params interface{}, res interface{}) error {
u, err := url.Parse(c.config.URL)
if err != nil {
return err
}
u.Path = path.Join(u.Path, uri)
values, ok := params.(url.Values)
if !ok {
return nil
}
var req *http.Request
var body io.Reader
if method == http.MethodGet {
u.RawQuery = values.Encode()
} else {
body = strings.NewReader(values.Encode())
}
req, err = http.NewRequest(method, u.String(), body)
if err != nil {
return err
}
req.Header.Set("User-Agent", userAgent)
if params != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
resp, err := ctxhttp.Do(ctx, &c.Client, req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return parseAPIError("bad request", resp)
} else if res == nil {
return nil
}
return json.NewDecoder(resp.Body).Decode(&res)
}
func (c *Client) newRequestWithFile(ctx context.Context, method string, uri string, params interface{}, res interface{}, file string) error {
u, err := url.Parse(c.config.URL)
if err != nil {
return err
}
u.Path = path.Join(u.Path, uri)
values, ok := params.(map[string]string)
if !ok {
return nil
}
var req *http.Request
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
for key, val := range values {
err := mw.WriteField(key, val)
if err != nil {
return err
}
}
header := make(textproto.MIMEHeader)
header.Add("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, file))
header.Add("Content-Type", "image/png")
fileWriter, err := mw.CreatePart(header)
if err != nil {
return err
}
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
io.Copy(fileWriter, f)
mw.Close()
req, err = http.NewRequest(method, u.String(), &buf)
if err != nil {
return err
}
req.Header.Add("Content-Type", "multipart/form-data; boundary="+mw.Boundary())
req.Header.Set("User-Agent", userAgent)
resp, err := ctxhttp.Do(ctx, &c.Client, req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return parseAPIError("bad request", resp)
} else if res == nil {
return nil
}
return json.NewDecoder(resp.Body).Decode(&res)
}
func parseAPIError(prefix string, resp *http.Response) error {
errMsg := fmt.Sprintf("%s: %s", prefix, resp.Status)
var e struct {
Error string `json:"error"`
}
json.NewDecoder(resp.Body).Decode(&e)
if e.Error != "" {
errMsg = fmt.Sprintf("%s: %s", errMsg, e.Error)
}
return errors.New(errMsg)
}