blob: 1eafbd2a07621c283c235d0212c209b49b035474 [file] [log] [blame]
Ash Wilson89466cc2014-08-29 11:27:39 -04001package gophercloud
2
Ash Wilson89eec332015-02-12 13:40:32 -05003import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "net/http"
Jon Perritt2b5e3e12015-02-13 12:15:08 -070010 "strings"
Ash Wilson89eec332015-02-12 13:40:32 -050011)
12
Jon Perritt2b5e3e12015-02-13 12:15:08 -070013// DefaultUserAgent is the default User-Agent string set in the request header.
14const DefaultUserAgent = "gophercloud/v1.0"
15
16// UserAgent represents a User-Agent header.
17type UserAgent struct {
18 // prepend is the slice of User-Agent strings to prepend to DefaultUserAgent.
19 // All the strings to prepend are accumulated and prepended in the Join method.
20 prepend []string
21}
22
23// Prepend prepends a user-defined string to the default User-Agent string. Users
24// may pass in one or more strings to prepend.
25func (ua *UserAgent) Prepend(s ...string) {
26 ua.prepend = append(s, ua.prepend...)
27}
28
29// Join concatenates all the user-defined User-Agend strings with the default
30// Gophercloud User-Agent string.
31func (ua *UserAgent) Join() string {
32 uaSlice := append(ua.prepend, DefaultUserAgent)
33 return strings.Join(uaSlice, " ")
34}
35
Jamie Hannafordb280dea2014-10-24 15:14:06 +020036// ProviderClient stores details that are required to interact with any
37// services within a specific provider's API.
Ash Wilson89466cc2014-08-29 11:27:39 -040038//
Jamie Hannafordb280dea2014-10-24 15:14:06 +020039// Generally, you acquire a ProviderClient by calling the NewClient method in
40// the appropriate provider's child package, providing whatever authentication
41// credentials are required.
Ash Wilson89466cc2014-08-29 11:27:39 -040042type ProviderClient struct {
Jamie Hannafordb280dea2014-10-24 15:14:06 +020043 // IdentityBase is the base URL used for a particular provider's identity
44 // service - it will be used when issuing authenticatation requests. It
45 // should point to the root resource of the identity service, not a specific
46 // identity version.
Ash Wilson09694b92014-09-09 14:08:27 -040047 IdentityBase string
48
Jamie Hannafordb280dea2014-10-24 15:14:06 +020049 // IdentityEndpoint is the identity endpoint. This may be a specific version
50 // of the identity service. If this is the case, this endpoint is used rather
51 // than querying versions first.
Ash Wilsonc6372fe2014-09-03 11:24:52 -040052 IdentityEndpoint string
53
Jamie Hannafordb280dea2014-10-24 15:14:06 +020054 // TokenID is the ID of the most recently issued valid token.
Ash Wilson89466cc2014-08-29 11:27:39 -040055 TokenID string
Ash Wilsonb8401a72014-09-08 17:07:49 -040056
Jamie Hannafordb280dea2014-10-24 15:14:06 +020057 // EndpointLocator describes how this provider discovers the endpoints for
58 // its constituent services.
Ash Wilsonb8401a72014-09-08 17:07:49 -040059 EndpointLocator EndpointLocator
Ash Wilson89eec332015-02-12 13:40:32 -050060
61 // HTTPClient allows users to interject arbitrary http, https, or other transit behaviors.
62 HTTPClient http.Client
Jon Perritt2b5e3e12015-02-13 12:15:08 -070063
64 // UserAgent represents the User-Agent header in the HTTP request.
65 UserAgent UserAgent
Jon Perrittf4052c62015-02-14 09:48:18 -070066
Jon Perrittb260acf2015-02-16 11:25:30 -070067 // AuthOptions is the user-provided options for authentication. This will be empty
68 // unless gophercloud.AuthOption.AllowReauth is set to true. This will be
69 // passed to ReauthFunc for re-authenticating when a user's token expires.
Jon Perrittf4052c62015-02-14 09:48:18 -070070 AuthOptions AuthOptions
71
72 // ReauthFunc is the function used to re-authenticate the user if the request
73 // fails with a 401 HTTP response code. This a needed because there may be multiple
74 // authentication functions for different Identity service versions.
75 ReauthFunc func(client *ProviderClient, options AuthOptions) error
Ash Wilson89466cc2014-08-29 11:27:39 -040076}
77
Jamie Hannafordb280dea2014-10-24 15:14:06 +020078// AuthenticatedHeaders returns a map of HTTP headers that are common for all
79// authenticated service requests.
Ash Wilson89466cc2014-08-29 11:27:39 -040080func (client *ProviderClient) AuthenticatedHeaders() map[string]string {
Ash Wilson89eec332015-02-12 13:40:32 -050081 if client.TokenID == "" {
82 return map[string]string{}
83 }
Ash Wilson89466cc2014-08-29 11:27:39 -040084 return map[string]string{"X-Auth-Token": client.TokenID}
85}
Ash Wilson89eec332015-02-12 13:40:32 -050086
87// RequestOpts customizes the behavior of the provider.Request() method.
88type RequestOpts struct {
89 // JSONBody, if provided, will be encoded as JSON and used as the body of the HTTP request. The
90 // content type of the request will default to "application/json" unless overridden by MoreHeaders.
91 // It's an error to specify both a JSONBody and a RawBody.
92 JSONBody interface{}
93 // RawBody contains an io.Reader that will be consumed by the request directly. No content-type
94 // will be set unless one is provided explicitly by MoreHeaders.
95 RawBody io.Reader
96
97 // JSONResponse, if provided, will be populated with the contents of the response body parsed as
98 // JSON.
Ash Wilson2491b4c2015-02-12 16:13:39 -050099 JSONResponse interface{}
Ash Wilson89eec332015-02-12 13:40:32 -0500100 // OkCodes contains a list of numeric HTTP status codes that should be interpreted as success. If
101 // the response has a different code, an error will be returned.
102 OkCodes []int
103
104 // MoreHeaders specifies additional HTTP headers to be provide on the request. If a header is
105 // provided with a blank value (""), that header will be *omitted* instead: use this to suppress
106 // the default Accept header or an inferred Content-Type, for example.
107 MoreHeaders map[string]string
108}
109
110// UnexpectedResponseCodeError is returned by the Request method when a response code other than
111// those listed in OkCodes is encountered.
112type UnexpectedResponseCodeError struct {
113 URL string
114 Method string
115 Expected []int
116 Actual int
117 Body []byte
118}
119
120func (err *UnexpectedResponseCodeError) Error() string {
121 return fmt.Sprintf(
122 "Expected HTTP response code %v when accessing [%s %s], but got %d instead\n%s",
123 err.Expected, err.Method, err.URL, err.Actual, err.Body,
124 )
125}
126
127var applicationJSON = "application/json"
128
129// Request performs an HTTP request using the ProviderClient's current HTTPClient. An authentication
130// header will automatically be provided.
131func (client *ProviderClient) Request(method, url string, options RequestOpts) (*http.Response, error) {
132 var body io.Reader
133 var contentType *string
134
135 // Derive the content body by either encoding an arbitrary object as JSON, or by taking a provided
136 // io.Reader as-is. Default the content-type to application/json.
Ash Wilson89eec332015-02-12 13:40:32 -0500137 if options.JSONBody != nil {
138 if options.RawBody != nil {
139 panic("Please provide only one of JSONBody or RawBody to gophercloud.Request().")
140 }
141
142 rendered, err := json.Marshal(options.JSONBody)
143 if err != nil {
144 return nil, err
145 }
146
147 body = bytes.NewReader(rendered)
148 contentType = &applicationJSON
149 }
150
151 if options.RawBody != nil {
152 body = options.RawBody
153 }
154
155 // Construct the http.Request.
Ash Wilson89eec332015-02-12 13:40:32 -0500156 req, err := http.NewRequest(method, url, body)
157 if err != nil {
158 return nil, err
159 }
160
161 // Populate the request headers. Apply options.MoreHeaders last, to give the caller the chance to
162 // modify or omit any header.
Ash Wilson89eec332015-02-12 13:40:32 -0500163 if contentType != nil {
Ash Wilson54d62fa2015-02-12 15:09:46 -0500164 req.Header.Set("Content-Type", *contentType)
Ash Wilson89eec332015-02-12 13:40:32 -0500165 }
Ash Wilson54d62fa2015-02-12 15:09:46 -0500166 req.Header.Set("Accept", applicationJSON)
Ash Wilson89eec332015-02-12 13:40:32 -0500167
168 for k, v := range client.AuthenticatedHeaders() {
169 req.Header.Add(k, v)
170 }
171
Jon Perrittf0a1fee2015-02-13 12:53:23 -0700172 // Set the User-Agent header
173 req.Header.Set("User-Agent", client.UserAgent.Join())
174
Ash Wilson89eec332015-02-12 13:40:32 -0500175 if options.MoreHeaders != nil {
176 for k, v := range options.MoreHeaders {
Ash Wilson54d62fa2015-02-12 15:09:46 -0500177 fmt.Printf("Applying header [%s: %v]\n", k, v)
Ash Wilson89eec332015-02-12 13:40:32 -0500178 if v != "" {
Ash Wilson54d62fa2015-02-12 15:09:46 -0500179 req.Header.Set(k, v)
Ash Wilson89eec332015-02-12 13:40:32 -0500180 } else {
181 req.Header.Del(k)
182 }
183 }
184 }
185
Jon Perritt2b5e3e12015-02-13 12:15:08 -0700186 // Issue the request.
Ash Wilson89eec332015-02-12 13:40:32 -0500187 resp, err := client.HTTPClient.Do(req)
188 if err != nil {
189 return nil, err
190 }
191
Jon Perrittf4052c62015-02-14 09:48:18 -0700192 if resp.StatusCode == 401 {
193 if client.AuthOptions.AllowReauth {
194 err = client.ReauthFunc(client, client.AuthOptions)
195 if err != nil {
196 return nil, fmt.Errorf("Error trying to re-authenticate: %s", err)
197 }
198 resp, err = client.Request(method, url, options)
199 if err != nil {
200 return nil, fmt.Errorf("Successfully re-authenticated, but got error executing request: %s", err)
201 }
202 }
203 }
204
Ash Wilson89eec332015-02-12 13:40:32 -0500205 // Validate the response code, if requested to do so.
Ash Wilson89eec332015-02-12 13:40:32 -0500206 if options.OkCodes != nil {
207 var ok bool
208 for _, code := range options.OkCodes {
209 if resp.StatusCode == code {
210 ok = true
211 break
212 }
213 }
214 if !ok {
215 body, _ := ioutil.ReadAll(resp.Body)
216 resp.Body.Close()
217 return resp, &UnexpectedResponseCodeError{
218 URL: url,
219 Method: method,
220 Expected: options.OkCodes,
221 Actual: resp.StatusCode,
222 Body: body,
223 }
224 }
225 }
226
227 // Parse the response body as JSON, if requested to do so.
Ash Wilson89eec332015-02-12 13:40:32 -0500228 if options.JSONResponse != nil {
229 defer resp.Body.Close()
230 json.NewDecoder(resp.Body).Decode(options.JSONResponse)
231 }
232
233 return resp, nil
234}