github.com/huaweicloud/golangsdk@v0.0.0-20210831081626-d823fe11ceba/openstack/bms/v2/keypairs/requests.go (about)

     1  package keypairs
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"github.com/huaweicloud/golangsdk"
     7  	"github.com/huaweicloud/golangsdk/pagination"
     8  )
     9  
    10  type ListOpts struct {
    11  	// Name is used to refer to this keypair from other services within this
    12  	// region.
    13  	Name string `json:"name"`
    14  }
    15  
    16  /// List returns a Pager that allows you to iterate over a collection of KeyPairs.
    17  func List(c *golangsdk.ServiceClient, opts ListOpts) ([]KeyPair, error) {
    18  	u := listURL(c)
    19  	pages, err := pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page {
    20  		return KeyPairPage{pagination.LinkedPageBase{PageResult: r}}
    21  	}).AllPages()
    22  	if err != nil {
    23  		return nil, err
    24  	}
    25  
    26  	allkeypairs, err := ExtractKeyPairs(pages)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  
    31  	return FilterKeyPairs(allkeypairs, opts)
    32  }
    33  
    34  //FilterKeyPairs used to filter keypairs using name
    35  func FilterKeyPairs(keypairs []KeyPair, opts ListOpts) ([]KeyPair, error) {
    36  
    37  	var refinedKeypairs []KeyPair
    38  	var matched bool
    39  	m := map[string]interface{}{}
    40  
    41  	if opts.Name != "" {
    42  		m["Name"] = opts.Name
    43  	}
    44  
    45  	if len(m) > 0 && len(keypairs) > 0 {
    46  		for _, keypair := range keypairs {
    47  			matched = true
    48  
    49  			for key, value := range m {
    50  				if sVal := getStructKeyPairField(&keypair, key); !(sVal == value) {
    51  					matched = false
    52  				}
    53  			}
    54  
    55  			if matched {
    56  				refinedKeypairs = append(refinedKeypairs, keypair)
    57  			}
    58  		}
    59  
    60  	} else {
    61  		refinedKeypairs = keypairs
    62  	}
    63  
    64  	return refinedKeypairs, nil
    65  }
    66  
    67  func getStructKeyPairField(v *KeyPair, field string) string {
    68  	r := reflect.ValueOf(v)
    69  	f := reflect.Indirect(r).FieldByName(field)
    70  	return string(f.String())
    71  }