github.com/dcarley/cf-cli@v6.24.1-0.20170220111324-4225ff346898+incompatible/api/cloudcontroller/ccv2/paginated_resources.go (about)

     1  package ccv2
     2  
     3  import (
     4  	"encoding/json"
     5  	"reflect"
     6  )
     7  
     8  // NewPaginatedResources returns a new PaginatedResources struct with the
     9  // given resource type.
    10  func NewPaginatedResources(exampleResource interface{}) PaginatedResources {
    11  	return PaginatedResources{
    12  		resourceType: reflect.TypeOf(exampleResource),
    13  	}
    14  }
    15  
    16  // PaginatedResources represents a page of resources returned by the Cloud
    17  // Controller.
    18  type PaginatedResources struct {
    19  	NextURL        string          `json:"next_url"`
    20  	ResourcesBytes json.RawMessage `json:"resources"`
    21  	resourceType   reflect.Type
    22  }
    23  
    24  // Resources unmarshals JSON representing a page of resources and returns a
    25  // slice of the given resource type.
    26  func (pr PaginatedResources) Resources() ([]interface{}, error) {
    27  	slicePtr := reflect.New(reflect.SliceOf(pr.resourceType))
    28  	err := json.Unmarshal([]byte(pr.ResourcesBytes), slicePtr.Interface())
    29  	slice := reflect.Indirect(slicePtr)
    30  
    31  	contents := make([]interface{}, 0, slice.Len())
    32  	for i := 0; i < slice.Len(); i++ {
    33  		contents = append(contents, slice.Index(i).Interface())
    34  	}
    35  	return contents, err
    36  }