Debian Codegraph @

fastly/client.go

raw symbols SCIP
1 package fastly
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "net/url"
10 "os"
11 "runtime"
12 "strings"
13
14 "github.com/ajg/form"
15 "github.com/google/jsonapi"
16 "github.com/hashicorp/go-cleanhttp"
17 "github.com/mitchellh/mapstructure"
18 )
19
20 // APIKeyEnvVar is the name of the environment variable where the Fastly API
21 // key should be read from.
22 const APIKeyEnvVar = "FASTLY_API_KEY"
23
24 // APIKeyHeader is the name of the header that contains the Fastly API key.
25 const APIKeyHeader = "Fastly-Key"
26
27 // DefaultEndpoint is the default endpoint for Fastly. Since Fastly does not
28 // support an on-premise solution, this is likely to always be the default.
29 const DefaultEndpoint = "https://api.fastly.com"
30
31 // RealtimeStatsEndpoint is the realtime stats endpoint for Fastly.
32 const RealtimeStatsEndpoint = "https://rt.fastly.com"
33
34 // ProjectURL is the url for this library.
35 var ProjectURL = "github.com/fastly/go-fastly"
36
37 // ProjectVersion is the version of this library.
38 var ProjectVersion = "1.2.1"
39
40 // UserAgent is the user agent for this particular client.
41 var UserAgent = fmt.Sprintf("FastlyGo/%s (+%s; %s)",
42 ProjectVersion, ProjectURL, runtime.Version())
43
44 // Client is the main entrypoint to the Fastly golang API library.
45 type Client struct {
46 // Address is the address of Fastly's API endpoint.
47 Address string
48
49 // HTTPClient is the HTTP client to use. If one is not provided, a default
50 // client will be used.
51 HTTPClient *http.Client
52
53 // apiKey is the Fastly API key to authenticate requests.
54 apiKey string
55
56 // url is the parsed URL from Address
57 url *url.URL
58 }
59
60 // RTSClient is the entrypoint to the Fastly's Realtime Stats API.
61 type RTSClient struct {
62 client *Client
63 }
64
65 // DefaultClient instantiates a new Fastly API client. This function requires
66 // the environment variable `FASTLY_API_KEY` is set and contains a valid API key
67 // to authenticate with Fastly.
68 func DefaultClient() *Client {
69 client, err := NewClient(os.Getenv(APIKeyEnvVar))
70 if err != nil {
71 panic(err)
72 }
73 return client
74 }
75
76 // NewClient creates a new API client with the given key and the default API
77 // endpoint. Because Fastly allows some requests without an API key, this
78 // function will not error if the API token is not supplied. Attempts to make a
79 // request that requires an API key will return a 403 response.
80 func NewClient(key string) (*Client, error) {
81 return NewClientForEndpoint(key, DefaultEndpoint)
82 }
83
84 // NewClientForEndpoint creates a new API client with the given key and API
85 // endpoint. Because Fastly allows some requests without an API key, this
86 // function will not error if the API token is not supplied. Attempts to make a
87 // request that requires an API key will return a 403 response.
88 func NewClientForEndpoint(key string, endpoint string) (*Client, error) {
89 client := &Client{apiKey: key, Address: endpoint}
90 return client.init()
91 }
92
93 // NewRealtimeStatsClient instantiates a new Fastly API client for the realtime stats.
94 // This function requires the environment variable `FASTLY_API_KEY` is set and contains
95 // a valid API key to authenticate with Fastly.
96 func NewRealtimeStatsClient() *RTSClient {
97 c, err := NewClientForEndpoint(os.Getenv(APIKeyEnvVar), RealtimeStatsEndpoint)
98 if err != nil {
99 panic(err)
100 }
101 return &RTSClient{client: c}
102 }
103
104 func (c *Client) init() (*Client, error) {
105 u, err := url.Parse(c.Address)
106 if err != nil {
107 return nil, err
108 }
109 c.url = u
110
111 if c.HTTPClient == nil {
112 c.HTTPClient = cleanhttp.DefaultClient()
113 }
114
115 return c, nil
116 }
117
118 // Get issues an HTTP GET request.
119 func (c *Client) Get(p string, ro *RequestOptions) (*http.Response, error) {
120 return c.Request("GET", p, ro)
121 }
122
123 // Head issues an HTTP HEAD request.
124 func (c *Client) Head(p string, ro *RequestOptions) (*http.Response, error) {
125 return c.Request("HEAD", p, ro)
126 }
127
128 // Patch issues an HTTP PATCH request.
129 func (c *Client) Patch(p string, ro *RequestOptions) (*http.Response, error) {
130 return c.Request("PATCH", p, ro)
131 }
132
133 // PatchForm issues an HTTP PUT request with the given interface form-encoded.
134 func (c *Client) PatchForm(p string, i interface{}, ro *RequestOptions) (*http.Response, error) {
135 return c.RequestForm("PATCH", p, i, ro)
136 }
137
138 // PatchJSON issues an HTTP PUT request with the given interface json-encoded.
139 func (c *Client) PatchJSON(p string, i interface{}, ro *RequestOptions) (*http.Response, error) {
140 return c.RequestJSON("PATCH", p, i, ro)
141 }
142
143 // PatchJSONAPI issues an HTTP PUT request with the given interface json-encoded.
144 func (c *Client) PatchJSONAPI(p string, i interface{}, ro *RequestOptions) (*http.Response, error) {
145 return c.RequestJSONAPI("PATCH", p, i, ro)
146 }
147
148 // Post issues an HTTP POST request.
149 func (c *Client) Post(p string, ro *RequestOptions) (*http.Response, error) {
150 return c.Request("POST", p, ro)
151 }
152
153 // PostForm issues an HTTP POST request with the given interface form-encoded.
154 func (c *Client) PostForm(p string, i interface{}, ro *RequestOptions) (*http.Response, error) {
155 return c.RequestForm("POST", p, i, ro)
156 }
157
158 // PostJSON issues an HTTP POST request with the given interface json-encoded.
159 func (c *Client) PostJSON(p string, i interface{}, ro *RequestOptions) (*http.Response, error) {
160 return c.RequestJSON("POST", p, i, ro)
161 }
162
163 // PostJSONAPI issues an HTTP POST request with the given interface json-encoded.
164 func (c *Client) PostJSONAPI(p string, i interface{}, ro *RequestOptions) (*http.Response, error) {
165 return c.RequestJSONAPI("POST", p, i, ro)
166 }
167
168 // Put issues an HTTP PUT request.
169 func (c *Client) Put(p string, ro *RequestOptions) (*http.Response, error) {
170 return c.Request("PUT", p, ro)
171 }
172
173 // PutForm issues an HTTP PUT request with the given interface form-encoded.
174 func (c *Client) PutForm(p string, i interface{}, ro *RequestOptions) (*http.Response, error) {
175 return c.RequestForm("PUT", p, i, ro)
176 }
177
178 // PutJSON issues an HTTP PUT request with the given interface json-encoded.
179 func (c *Client) PutJSON(p string, i interface{}, ro *RequestOptions) (*http.Response, error) {
180 return c.RequestJSON("PUT", p, i, ro)
181 }
182
183 // PutJSONAPI issues an HTTP PUT request with the given interface json-encoded.
184 func (c *Client) PutJSONAPI(p string, i interface{}, ro *RequestOptions) (*http.Response, error) {
185 return c.RequestJSONAPI("PUT", p, i, ro)
186 }
187
188 // Delete issues an HTTP DELETE request.
189 func (c *Client) Delete(p string, ro *RequestOptions) (*http.Response, error) {
190 return c.Request("DELETE", p, ro)
191 }
192
193 // Request makes an HTTP request against the HTTPClient using the given verb,
194 // Path, and request options.
195 func (c *Client) Request(verb, p string, ro *RequestOptions) (*http.Response, error) {
196 req, err := c.RawRequest(verb, p, ro)
197 if err != nil {
198 return nil, err
199 }
200
201 resp, err := checkResp(c.HTTPClient.Do(req))
202 if err != nil {
203 return resp, err
204 }
205
206 return resp, nil
207 }
208
209 // RequestForm makes an HTTP request with the given interface being encoded as
210 // form data.
211 func (c *Client) RequestForm(verb, p string, i interface{}, ro *RequestOptions) (*http.Response, error) {
212 if ro == nil {
213 ro = new(RequestOptions)
214 }
215
216 if ro.Headers == nil {
217 ro.Headers = make(map[string]string)
218 }
219 ro.Headers["Content-Type"] = "application/x-www-form-urlencoded"
220
221 buf := new(bytes.Buffer)
222 if err := form.NewEncoder(buf).KeepZeros(true).DelimitWith('|').Encode(i); err != nil {
223 return nil, err
224 }
225 body := buf.String()
226
227 ro.Body = strings.NewReader(body)
228 ro.BodyLength = int64(len(body))
229
230 return c.Request(verb, p, ro)
231 }
232
233 func (c *Client) RequestJSON(verb, p string, i interface{}, ro *RequestOptions) (*http.Response, error) {
234 if ro == nil {
235 ro = new(RequestOptions)
236 }
237
238 if ro.Headers == nil {
239 ro.Headers = make(map[string]string)
240 }
241 ro.Headers["Content-Type"] = "application/json"
242 ro.Headers["Accept"] = "application/json"
243
244 body, err := json.Marshal(i)
245 if err != nil {
246 return nil, err
247 }
248
249 ro.Body = bytes.NewReader(body)
250 ro.BodyLength = int64(len(body))
251
252 return c.Request(verb, p, ro)
253 }
254
255 func (c *Client) RequestJSONAPI(verb, p string, i interface{}, ro *RequestOptions) (*http.Response, error) {
256 if ro == nil {
257 ro = new(RequestOptions)
258 }
259
260 if ro.Headers == nil {
261 ro.Headers = make(map[string]string)
262 }
263 ro.Headers["Content-Type"] = jsonapi.MediaType
264 ro.Headers["Accept"] = jsonapi.MediaType
265
266 var buf bytes.Buffer
267 if err := jsonapi.MarshalPayload(&buf, i); err != nil {
268 return nil, err
269 }
270
271 ro.Body = &buf
272 ro.BodyLength = int64(buf.Len())
273
274 return c.Request(verb, p, ro)
275 }
276
277 // checkResp wraps an HTTP request from the default client and verifies that the
278 // request was successful. A non-200 request returns an error formatted to
279 // included any validation problems or otherwise.
280 func checkResp(resp *http.Response, err error) (*http.Response, error) {
281 // If the err is already there, there was an error higher up the chain, so
282 // just return that.
283 if err != nil {
284 return resp, err
285 }
286
287 switch resp.StatusCode {
288 case 200, 201, 202, 204, 205, 206:
289 return resp, nil
290 default:
291 return resp, NewHTTPError(resp)
292 }
293 }
294
295 // decodeJSON is used to decode an HTTP response body into an interface as JSON.
296 func decodeJSON(out interface{}, body io.ReadCloser) error {
297 defer body.Close()
298
299 var parsed interface{}
300 dec := json.NewDecoder(body)
301 if err := dec.Decode(&parsed); err != nil {
302 return err
303 }
304
305 decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
306 DecodeHook: mapstructure.ComposeDecodeHookFunc(
307 mapToHTTPHeaderHookFunc(),
308 stringToTimeHookFunc(),
309 ),
310 WeaklyTypedInput: true,
311 Result: out,
312 })
313 if err != nil {
314 return err
315 }
316 return decoder.Decode(parsed)
317 }