-
Notifications
You must be signed in to change notification settings - Fork 232
/
client.go
109 lines (94 loc) · 2.3 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
package rest
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/CircleCI-Public/circleci-cli/version"
)
type Client struct {
baseURL *url.URL
circleToken string
client *http.Client
}
func New(host, endpoint, circleToken string) *Client {
// Ensure endpoint ends with a slash
if !strings.HasSuffix(endpoint, "/") {
endpoint += "/"
}
u, _ := url.Parse(host)
return &Client{
baseURL: u.ResolveReference(&url.URL{Path: endpoint}),
circleToken: circleToken,
client: &http.Client{
Timeout: 10 * time.Second,
},
}
}
func (c *Client) NewRequest(method string, u *url.URL, payload interface{}) (req *http.Request, err error) {
var r io.Reader
if payload != nil {
buf := &bytes.Buffer{}
r = buf
err = json.NewEncoder(buf).Encode(payload)
if err != nil {
return nil, err
}
}
req, err = http.NewRequest(method, c.baseURL.ResolveReference(u).String(), r)
if err != nil {
return nil, err
}
req.Header.Set("Circle-Token", c.circleToken)
req.Header.Set("Accept-Type", "application/json")
req.Header.Set("User-Agent", version.UserAgent())
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
return req, nil
}
func (c *Client) DoRequest(req *http.Request, resp interface{}) (statusCode int, err error) {
httpResp, err := c.client.Do(req)
if err != nil {
return 0, err
}
defer httpResp.Body.Close()
if httpResp.StatusCode >= 300 {
httpError := struct {
Message string `json:"message"`
}{}
err = json.NewDecoder(httpResp.Body).Decode(&httpError)
if err != nil {
return httpResp.StatusCode, err
}
return httpResp.StatusCode, &HTTPError{Code: httpResp.StatusCode, Message: httpError.Message}
}
if resp != nil {
if !strings.Contains(httpResp.Header.Get("Content-Type"), "application/json") {
return httpResp.StatusCode, errors.New("wrong content type received")
}
err = json.NewDecoder(httpResp.Body).Decode(resp)
if err != nil {
return httpResp.StatusCode, err
}
}
return httpResp.StatusCode, nil
}
type HTTPError struct {
Code int
Message string
}
func (e *HTTPError) Error() string {
if e.Code == 0 {
e.Code = http.StatusInternalServerError
}
if e.Message != "" {
return e.Message
}
return fmt.Sprintf("response %d (%s)", e.Code, http.StatusText(e.Code))
}