Ash Wilson | 89466cc | 2014-08-29 11:27:39 -0400 | [diff] [blame] | 1 | package gophercloud |
| 2 | |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "io/ioutil" |
| 9 | "net/http" |
Jon Perritt | 2b5e3e1 | 2015-02-13 12:15:08 -0700 | [diff] [blame^] | 10 | "strings" |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 11 | ) |
| 12 | |
Jon Perritt | 2b5e3e1 | 2015-02-13 12:15:08 -0700 | [diff] [blame^] | 13 | // DefaultUserAgent is the default User-Agent string set in the request header. |
| 14 | const DefaultUserAgent = "gophercloud/v1.0" |
| 15 | |
| 16 | // UserAgent represents a User-Agent header. |
| 17 | type 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. |
| 25 | func (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. |
| 31 | func (ua *UserAgent) Join() string { |
| 32 | uaSlice := append(ua.prepend, DefaultUserAgent) |
| 33 | return strings.Join(uaSlice, " ") |
| 34 | } |
| 35 | |
Jamie Hannaford | b280dea | 2014-10-24 15:14:06 +0200 | [diff] [blame] | 36 | // ProviderClient stores details that are required to interact with any |
| 37 | // services within a specific provider's API. |
Ash Wilson | 89466cc | 2014-08-29 11:27:39 -0400 | [diff] [blame] | 38 | // |
Jamie Hannaford | b280dea | 2014-10-24 15:14:06 +0200 | [diff] [blame] | 39 | // 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 Wilson | 89466cc | 2014-08-29 11:27:39 -0400 | [diff] [blame] | 42 | type ProviderClient struct { |
Jamie Hannaford | b280dea | 2014-10-24 15:14:06 +0200 | [diff] [blame] | 43 | // 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 Wilson | 09694b9 | 2014-09-09 14:08:27 -0400 | [diff] [blame] | 47 | IdentityBase string |
| 48 | |
Jamie Hannaford | b280dea | 2014-10-24 15:14:06 +0200 | [diff] [blame] | 49 | // 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 Wilson | c6372fe | 2014-09-03 11:24:52 -0400 | [diff] [blame] | 52 | IdentityEndpoint string |
| 53 | |
Jamie Hannaford | b280dea | 2014-10-24 15:14:06 +0200 | [diff] [blame] | 54 | // TokenID is the ID of the most recently issued valid token. |
Ash Wilson | 89466cc | 2014-08-29 11:27:39 -0400 | [diff] [blame] | 55 | TokenID string |
Ash Wilson | b8401a7 | 2014-09-08 17:07:49 -0400 | [diff] [blame] | 56 | |
Jamie Hannaford | b280dea | 2014-10-24 15:14:06 +0200 | [diff] [blame] | 57 | // EndpointLocator describes how this provider discovers the endpoints for |
| 58 | // its constituent services. |
Ash Wilson | b8401a7 | 2014-09-08 17:07:49 -0400 | [diff] [blame] | 59 | EndpointLocator EndpointLocator |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 60 | |
| 61 | // HTTPClient allows users to interject arbitrary http, https, or other transit behaviors. |
| 62 | HTTPClient http.Client |
Jon Perritt | 2b5e3e1 | 2015-02-13 12:15:08 -0700 | [diff] [blame^] | 63 | |
| 64 | // UserAgent represents the User-Agent header in the HTTP request. |
| 65 | UserAgent UserAgent |
Ash Wilson | 89466cc | 2014-08-29 11:27:39 -0400 | [diff] [blame] | 66 | } |
| 67 | |
Jamie Hannaford | b280dea | 2014-10-24 15:14:06 +0200 | [diff] [blame] | 68 | // AuthenticatedHeaders returns a map of HTTP headers that are common for all |
| 69 | // authenticated service requests. |
Ash Wilson | 89466cc | 2014-08-29 11:27:39 -0400 | [diff] [blame] | 70 | func (client *ProviderClient) AuthenticatedHeaders() map[string]string { |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 71 | if client.TokenID == "" { |
| 72 | return map[string]string{} |
| 73 | } |
Ash Wilson | 89466cc | 2014-08-29 11:27:39 -0400 | [diff] [blame] | 74 | return map[string]string{"X-Auth-Token": client.TokenID} |
| 75 | } |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 76 | |
| 77 | // RequestOpts customizes the behavior of the provider.Request() method. |
| 78 | type RequestOpts struct { |
| 79 | // JSONBody, if provided, will be encoded as JSON and used as the body of the HTTP request. The |
| 80 | // content type of the request will default to "application/json" unless overridden by MoreHeaders. |
| 81 | // It's an error to specify both a JSONBody and a RawBody. |
| 82 | JSONBody interface{} |
| 83 | // RawBody contains an io.Reader that will be consumed by the request directly. No content-type |
| 84 | // will be set unless one is provided explicitly by MoreHeaders. |
| 85 | RawBody io.Reader |
| 86 | |
| 87 | // JSONResponse, if provided, will be populated with the contents of the response body parsed as |
| 88 | // JSON. |
Ash Wilson | 2491b4c | 2015-02-12 16:13:39 -0500 | [diff] [blame] | 89 | JSONResponse interface{} |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 90 | // OkCodes contains a list of numeric HTTP status codes that should be interpreted as success. If |
| 91 | // the response has a different code, an error will be returned. |
| 92 | OkCodes []int |
| 93 | |
| 94 | // MoreHeaders specifies additional HTTP headers to be provide on the request. If a header is |
| 95 | // provided with a blank value (""), that header will be *omitted* instead: use this to suppress |
| 96 | // the default Accept header or an inferred Content-Type, for example. |
| 97 | MoreHeaders map[string]string |
| 98 | } |
| 99 | |
| 100 | // UnexpectedResponseCodeError is returned by the Request method when a response code other than |
| 101 | // those listed in OkCodes is encountered. |
| 102 | type UnexpectedResponseCodeError struct { |
| 103 | URL string |
| 104 | Method string |
| 105 | Expected []int |
| 106 | Actual int |
| 107 | Body []byte |
| 108 | } |
| 109 | |
| 110 | func (err *UnexpectedResponseCodeError) Error() string { |
| 111 | return fmt.Sprintf( |
| 112 | "Expected HTTP response code %v when accessing [%s %s], but got %d instead\n%s", |
| 113 | err.Expected, err.Method, err.URL, err.Actual, err.Body, |
| 114 | ) |
| 115 | } |
| 116 | |
| 117 | var applicationJSON = "application/json" |
| 118 | |
| 119 | // Request performs an HTTP request using the ProviderClient's current HTTPClient. An authentication |
| 120 | // header will automatically be provided. |
| 121 | func (client *ProviderClient) Request(method, url string, options RequestOpts) (*http.Response, error) { |
| 122 | var body io.Reader |
| 123 | var contentType *string |
| 124 | |
| 125 | // Derive the content body by either encoding an arbitrary object as JSON, or by taking a provided |
| 126 | // io.Reader as-is. Default the content-type to application/json. |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 127 | if options.JSONBody != nil { |
| 128 | if options.RawBody != nil { |
| 129 | panic("Please provide only one of JSONBody or RawBody to gophercloud.Request().") |
| 130 | } |
| 131 | |
| 132 | rendered, err := json.Marshal(options.JSONBody) |
| 133 | if err != nil { |
| 134 | return nil, err |
| 135 | } |
| 136 | |
| 137 | body = bytes.NewReader(rendered) |
| 138 | contentType = &applicationJSON |
| 139 | } |
| 140 | |
| 141 | if options.RawBody != nil { |
| 142 | body = options.RawBody |
| 143 | } |
| 144 | |
| 145 | // Construct the http.Request. |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 146 | req, err := http.NewRequest(method, url, body) |
| 147 | if err != nil { |
| 148 | return nil, err |
| 149 | } |
| 150 | |
| 151 | // Populate the request headers. Apply options.MoreHeaders last, to give the caller the chance to |
| 152 | // modify or omit any header. |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 153 | if contentType != nil { |
Ash Wilson | 54d62fa | 2015-02-12 15:09:46 -0500 | [diff] [blame] | 154 | req.Header.Set("Content-Type", *contentType) |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 155 | } |
Ash Wilson | 54d62fa | 2015-02-12 15:09:46 -0500 | [diff] [blame] | 156 | req.Header.Set("Accept", applicationJSON) |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 157 | |
| 158 | for k, v := range client.AuthenticatedHeaders() { |
| 159 | req.Header.Add(k, v) |
| 160 | } |
| 161 | |
| 162 | if options.MoreHeaders != nil { |
| 163 | for k, v := range options.MoreHeaders { |
Ash Wilson | 54d62fa | 2015-02-12 15:09:46 -0500 | [diff] [blame] | 164 | fmt.Printf("Applying header [%s: %v]\n", k, v) |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 165 | if v != "" { |
Ash Wilson | 54d62fa | 2015-02-12 15:09:46 -0500 | [diff] [blame] | 166 | req.Header.Set(k, v) |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 167 | } else { |
| 168 | req.Header.Del(k) |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | |
Jon Perritt | 2b5e3e1 | 2015-02-13 12:15:08 -0700 | [diff] [blame^] | 173 | // Set user-agent header |
| 174 | req.Header.Set("User-Agent", client.UserAgent.Join()) |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 175 | |
Jon Perritt | 2b5e3e1 | 2015-02-13 12:15:08 -0700 | [diff] [blame^] | 176 | // Issue the request. |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 177 | resp, err := client.HTTPClient.Do(req) |
| 178 | if err != nil { |
| 179 | return nil, err |
| 180 | } |
| 181 | |
| 182 | // Validate the response code, if requested to do so. |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 183 | if options.OkCodes != nil { |
| 184 | var ok bool |
| 185 | for _, code := range options.OkCodes { |
| 186 | if resp.StatusCode == code { |
| 187 | ok = true |
| 188 | break |
| 189 | } |
| 190 | } |
| 191 | if !ok { |
| 192 | body, _ := ioutil.ReadAll(resp.Body) |
| 193 | resp.Body.Close() |
| 194 | return resp, &UnexpectedResponseCodeError{ |
| 195 | URL: url, |
| 196 | Method: method, |
| 197 | Expected: options.OkCodes, |
| 198 | Actual: resp.StatusCode, |
| 199 | Body: body, |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | // Parse the response body as JSON, if requested to do so. |
Ash Wilson | 89eec33 | 2015-02-12 13:40:32 -0500 | [diff] [blame] | 205 | if options.JSONResponse != nil { |
| 206 | defer resp.Body.Close() |
| 207 | json.NewDecoder(resp.Body).Decode(options.JSONResponse) |
| 208 | } |
| 209 | |
| 210 | return resp, nil |
| 211 | } |