/
api.go
206 lines (172 loc) · 4.84 KB
/
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
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
// api provides common functionality for all the iron.io APIs
package api
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"time"
"github.com/iron-io/iron_go/config"
)
type URL struct {
URL url.URL
Settings config.Settings
}
var (
debug bool
// HttpClient is the client used by iron_go to make each http request. It is exported in case
// the client would like to modify it from the default behavior from http.DefaultClient.
HttpClient = &http.Client{}
)
func dbg(v ...interface{}) {
if debug {
fmt.Fprintln(os.Stderr, v...)
}
}
func init() {
if os.Getenv("IRON_API_DEBUG") != "" {
debug = true
dbg("debugging of api enabled")
}
}
func Action(cs config.Settings, prefix string, suffix ...string) *URL {
parts := append([]string{prefix}, suffix...)
return ActionEndpoint(cs, strings.Join(parts, "/"))
}
func ActionEndpoint(cs config.Settings, endpoint string) *URL {
u := &URL{Settings: cs, URL: url.URL{}}
u.URL.Scheme = cs.Scheme
u.URL.Host = fmt.Sprintf("%s:%d", cs.Host, cs.Port)
u.URL.Path = fmt.Sprintf("/%s/projects/%s/%s", cs.ApiVersion, cs.ProjectId, endpoint)
return u
}
func VersionAction(cs config.Settings) *URL {
u := &URL{Settings: cs, URL: url.URL{Scheme: cs.Scheme}}
u.URL.Host = fmt.Sprintf("%s:%d", cs.Host, cs.Port)
u.URL.Path = "/version"
return u
}
func (u *URL) QueryAdd(key string, format string, value interface{}) *URL {
query := u.URL.Query()
query.Add(key, fmt.Sprintf(format, value))
u.URL.RawQuery = query.Encode()
return u
}
func (u *URL) Req(method string, in, out interface{}) (err error) {
var reqBody io.Reader
if in != nil {
data, err := json.Marshal(in)
if err != nil {
return err
}
reqBody = bytes.NewBuffer(data)
}
response, err := u.Request(method, reqBody)
if response != nil {
defer response.Body.Close()
}
if err == nil && out != nil {
err = json.NewDecoder(response.Body).Decode(out)
dbg("u:", u, "out:", fmt.Sprintf("%#v\n", out))
}
return
}
var MaxRequestRetries = 5
func (u *URL) Request(method string, body io.Reader) (response *http.Response, err error) {
var bodyBytes []byte
if body == nil {
bodyBytes = []byte{}
} else {
bodyBytes, err = ioutil.ReadAll(body)
if err != nil {
return nil, err
}
}
request, err := http.NewRequest(method, u.URL.String(), nil)
if err != nil {
return nil, err
}
request.Header.Set("Authorization", "OAuth "+u.Settings.Token)
request.Header.Set("Accept", "application/json")
request.Header.Set("User-Agent", u.Settings.UserAgent)
if body != nil {
request.Header.Set("Content-Type", "application/json")
}
dbg("request:", fmt.Sprintf("%#v\n", request))
for tries := 0; tries <= MaxRequestRetries; tries++ {
request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
response, err = HttpClient.Do(request)
if err != nil {
if err == io.EOF {
continue
}
return
}
if response.StatusCode == http.StatusServiceUnavailable {
delay := (tries + 1) * 10 // smooth out delays from 0-2
time.Sleep(time.Duration(delay*delay) * time.Millisecond)
continue
}
break
}
// DumpResponse(response)
if err = ResponseAsError(response); err != nil {
return
}
return
}
func DumpRequest(req *http.Request) {
out, err := httputil.DumpRequestOut(req, true)
if err != nil {
panic(err)
}
fmt.Printf("%q\n", out)
}
func DumpResponse(response *http.Response) {
out, err := httputil.DumpResponse(response, true)
if err != nil {
panic(err)
}
fmt.Printf("%q\n", out)
}
var HTTPErrorDescriptions = map[int]string{
http.StatusUnauthorized: "The OAuth token is either not provided or invalid",
http.StatusNotFound: "The resource, project, or endpoint being requested doesn't exist.",
http.StatusMethodNotAllowed: "This endpoint doesn't support that particular verb",
http.StatusNotAcceptable: "Required fields are missing",
}
func ResponseAsError(response *http.Response) HTTPResponseError {
if response.StatusCode == http.StatusOK || response.StatusCode == http.StatusCreated {
return nil
}
defer response.Body.Close()
desc, found := HTTPErrorDescriptions[response.StatusCode]
if found {
return resErr{response: response, error: response.Status + ": " + desc}
}
out := map[string]interface{}{}
err := json.NewDecoder(response.Body).Decode(&out)
if err != nil {
return resErr{response: response, error: fmt.Sprint(response.Status, ": ", err.Error())}
}
if msg, ok := out["msg"]; ok {
return resErr{response: response, error: fmt.Sprint(response.Status, ": ", msg)}
}
return resErr{response: response, error: response.Status + ": Unknown API Response"}
}
type HTTPResponseError interface {
Error() string
Response() *http.Response
}
type resErr struct {
error string
response *http.Response
}
func (h resErr) Error() string { return h.error }
func (h resErr) Response() *http.Response { return h.response }