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