Ash Wilson | 1f11051 | 2014-10-02 15:43:47 -0400 | [diff] [blame] | 1 | package tenants |
| 2 | |
| 3 | import ( |
Ash Wilson | 9d085a8 | 2014-10-03 13:05:03 -0400 | [diff] [blame] | 4 | "fmt" |
| 5 | |
Ash Wilson | 1f11051 | 2014-10-02 15:43:47 -0400 | [diff] [blame] | 6 | "github.com/mitchellh/mapstructure" |
| 7 | "github.com/rackspace/gophercloud/pagination" |
| 8 | ) |
| 9 | |
| 10 | // Tenant is a grouping of users in the identity service. |
| 11 | type Tenant struct { |
| 12 | // ID is a unique identifier for this tenant. |
| 13 | ID string `mapstructure:"id"` |
| 14 | |
| 15 | // Name is a friendlier user-facing name for this tenant. |
| 16 | Name string `mapstructure:"name"` |
| 17 | |
| 18 | // Description is a human-readable explanation of this Tenant's purpose. |
| 19 | Description string `mapstructure:"description"` |
| 20 | |
| 21 | // Enabled indicates whether or not a tenant is active. |
| 22 | Enabled bool `mapstructure:"enabled"` |
| 23 | } |
| 24 | |
| 25 | // TenantPage is a single page of Tenant results. |
| 26 | type TenantPage struct { |
| 27 | pagination.LinkedPageBase |
| 28 | } |
| 29 | |
| 30 | // IsEmpty determines whether or not a page of Tenants contains any results. |
| 31 | func (page TenantPage) IsEmpty() (bool, error) { |
| 32 | tenants, err := ExtractTenants(page) |
| 33 | if err != nil { |
| 34 | return false, err |
| 35 | } |
| 36 | return len(tenants) == 0, nil |
| 37 | } |
| 38 | |
| 39 | // NextPageURL extracts the "next" link from the tenants_links section of the result. |
| 40 | func (page TenantPage) NextPageURL() (string, error) { |
| 41 | type link struct { |
| 42 | Href string `mapstructure:"href"` |
| 43 | Rel string `mapstructure:"rel"` |
| 44 | } |
| 45 | type resp struct { |
| 46 | Links []link `mapstructure:"tenants_links"` |
| 47 | } |
| 48 | |
| 49 | var r resp |
| 50 | err := mapstructure.Decode(page.Body, &r) |
| 51 | if err != nil { |
| 52 | return "", err |
| 53 | } |
| 54 | |
| 55 | var url string |
| 56 | for _, l := range r.Links { |
| 57 | if l.Rel == "next" { |
| 58 | url = l.Href |
| 59 | } |
| 60 | } |
| 61 | if url == "" { |
| 62 | return "", nil |
| 63 | } |
| 64 | |
| 65 | return url, nil |
| 66 | } |
| 67 | |
| 68 | // ExtractTenants returns a slice of Tenants contained in a single page of results. |
| 69 | func ExtractTenants(page pagination.Page) ([]Tenant, error) { |
| 70 | casted := page.(TenantPage).Body |
| 71 | var response struct { |
| 72 | Tenants []Tenant `mapstructure:"tenants"` |
| 73 | } |
| 74 | |
Ash Wilson | 9d085a8 | 2014-10-03 13:05:03 -0400 | [diff] [blame] | 75 | fmt.Printf("Decode %#v => %#v\n", casted, response) |
Ash Wilson | 1f11051 | 2014-10-02 15:43:47 -0400 | [diff] [blame] | 76 | err := mapstructure.Decode(casted, &response) |
| 77 | return response.Tenants, err |
| 78 | } |