Debian Codegraph @

fastly/request.go

raw symbols SCIP
1 package fastly
2
3 import (
4 "io"
5 "net/http"
6 "net/url"
7 "strings"
8 )
9
10 // RequestOptions is the list of options to pass to the request.
11 type RequestOptions struct {
12 // Params is a map of key-value pairs that will be added to the Request.
13 Params map[string]string
14
15 // Headers is a map of key-value pairs that will be added to the Request.
16 Headers map[string]string
17
18 // Body is an io.Reader object that will be streamed or uploaded with the
19 // Request. BodyLength is the final size of the Body.
20 Body io.Reader
21 BodyLength int64
22 }
23
24 // RawRequest accepts a verb, URL, and RequestOptions struct and returns the
25 // constructed http.Request and any errors that occurred
26 func (c *Client) RawRequest(verb, p string, ro *RequestOptions) (*http.Request, error) {
27 // Ensure we have request options.
28 if ro == nil {
29 ro = new(RequestOptions)
30 }
31
32 // Append the path to the URL.
33 u := strings.TrimRight(c.url.String(), "/") + "/" + strings.TrimLeft(p, "/")
34
35 // Create the request object.
36 request, err := http.NewRequest(verb, u, ro.Body)
37 if err != nil {
38 return nil, err
39 }
40
41 var params = make(url.Values)
42 for k, v := range ro.Params {
43 params.Add(k, v)
44 }
45 request.URL.RawQuery = params.Encode()
46
47 // Set the API key.
48 if len(c.apiKey) > 0 {
49 request.Header.Set(APIKeyHeader, c.apiKey)
50 }
51
52 // Set the User-Agent.
53 request.Header.Set("User-Agent", UserAgent)
54
55 // Add any custom headers.
56 for k, v := range ro.Headers {
57 request.Header.Add(k, v)
58 }
59
60 // Add Content-Length if we have it.
61 if ro.BodyLength > 0 {
62 request.ContentLength = ro.BodyLength
63 }
64
65 return request, nil
66 }
67
68 // SimpleGet combines the RawRequest and Request methods,
69 // but doesn't add any parameters or change any encoding in the URL
70 // passed to it. It's mostly for calling the URLs given to us
71 // directly from Fastly without mangling them.
72 func (c *Client) SimpleGet(target string) (*http.Response, error) {
73 // We parse the URL and then convert it right back to a string
74 // later; this just acts as a check that Fastly isn't sending
75 // us nonsense.
76 url, err := url.Parse(target)
77 if err != nil {
78 return nil, err
79 }
80
81 request, err := http.NewRequest("GET", url.String(), nil)
82 if err != nil {
83 return nil, err
84 }
85
86 if len(c.apiKey) > 0 {
87 request.Header.Set(APIKeyHeader, c.apiKey)
88 }
89 request.Header.Set("User-Agent", UserAgent)
90
91 resp, err := checkResp(c.HTTPClient.Do(request))
92 if err != nil {
93 return resp, err
94 }
95 return resp, nil
96 }