-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient_api.go
67 lines (56 loc) · 1.36 KB
/
client_api.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
package cloudflare
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"golang.org/x/net/context"
)
var baseURL = "https://api.cloudflare.com/client/v4"
func apiURL(format string, a ...interface{}) string {
return fmt.Sprintf("%s%s", baseURL, fmt.Sprintf(format, a...))
}
func readResponse(r io.Reader) (result *Response, err error) {
result = new(Response)
err = json.NewDecoder(r).Decode(result)
if err != nil {
return nil, err
} else if err := result.Err(); err != nil {
return nil, err
}
return
}
type httpResponse struct {
resp *http.Response
err error
}
func httpDo(ctx context.Context, opts *Options, method, url string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Auth-Email", opts.Email)
req.Header.Set("X-Auth-Key", opts.Key)
transport := &http.Transport{}
client := &http.Client{Transport: transport}
respchan := make(chan *httpResponse, 1)
go func() {
resp, err := client.Do(req)
if err == nil {
if resp.ContentLength == 0 {
err = errors.New("empty response body")
}
}
respchan <- &httpResponse{resp: resp, err: err}
}()
select {
case <-ctx.Done():
transport.CancelRequest(req)
<-respchan
return nil, ctx.Err()
case r := <-respchan:
return r.resp, r.err
}
}