Ash Wilson | 61dcb02 | 2014-10-03 08:15:47 -0400 | [diff] [blame] | 1 | package extensions |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | |
| 6 | "github.com/mitchellh/mapstructure" |
| 7 | "github.com/rackspace/gophercloud" |
| 8 | "github.com/rackspace/gophercloud/pagination" |
| 9 | ) |
| 10 | |
Jamie Hannaford | 35c91a6 | 2014-10-06 15:50:08 +0200 | [diff] [blame] | 11 | // GetResult temporarily stores the result of a Get call. |
Ash Wilson | 61dcb02 | 2014-10-03 08:15:47 -0400 | [diff] [blame] | 12 | // Use its Extract() method to interpret it as an Extension. |
| 13 | type GetResult struct { |
| 14 | gophercloud.CommonResult |
| 15 | } |
| 16 | |
| 17 | // Extract interprets a GetResult as an Extension. |
| 18 | func (r GetResult) Extract() (*Extension, error) { |
| 19 | if r.Err != nil { |
| 20 | return nil, r.Err |
| 21 | } |
| 22 | |
| 23 | var res struct { |
| 24 | Extension *Extension `json:"extension"` |
| 25 | } |
| 26 | |
| 27 | err := mapstructure.Decode(r.Resp, &res) |
| 28 | if err != nil { |
| 29 | return nil, fmt.Errorf("Error decoding OpenStack extension: %v", err) |
| 30 | } |
| 31 | |
| 32 | return res.Extension, nil |
| 33 | } |
| 34 | |
| 35 | // Extension is a struct that represents an OpenStack extension. |
| 36 | type Extension struct { |
| 37 | Updated string `json:"updated"` |
| 38 | Name string `json:"name"` |
| 39 | Links []interface{} `json:"links"` |
| 40 | Namespace string `json:"namespace"` |
| 41 | Alias string `json:"alias"` |
| 42 | Description string `json:"description"` |
| 43 | } |
| 44 | |
| 45 | // ExtensionPage is the page returned by a pager when traversing over a collection of extensions. |
| 46 | type ExtensionPage struct { |
| 47 | pagination.SinglePageBase |
| 48 | } |
| 49 | |
| 50 | // IsEmpty checks whether an ExtensionPage struct is empty. |
| 51 | func (r ExtensionPage) IsEmpty() (bool, error) { |
| 52 | is, err := ExtractExtensions(r) |
| 53 | if err != nil { |
| 54 | return true, err |
| 55 | } |
| 56 | return len(is) == 0, nil |
| 57 | } |
| 58 | |
| 59 | // ExtractExtensions accepts a Page struct, specifically an ExtensionPage struct, and extracts the |
| 60 | // elements into a slice of Extension structs. |
| 61 | // In other words, a generic collection is mapped into a relevant slice. |
| 62 | func ExtractExtensions(page pagination.Page) ([]Extension, error) { |
| 63 | var resp struct { |
| 64 | Extensions []Extension `mapstructure:"extensions"` |
| 65 | } |
| 66 | |
| 67 | err := mapstructure.Decode(page.(ExtensionPage).Body, &resp) |
| 68 | if err != nil { |
| 69 | return nil, err |
| 70 | } |
| 71 | |
| 72 | return resp.Extensions, nil |
| 73 | } |