github.com/opentelekomcloud/gophertelekomcloud@v0.9.3/openstack/bms/v2/nics/list.go (about) 1 package nics 2 3 import ( 4 "reflect" 5 6 "github.com/opentelekomcloud/gophertelekomcloud" 7 "github.com/opentelekomcloud/gophertelekomcloud/pagination" 8 ) 9 10 // ListOpts allows the filtering and sorting of paginated collections through 11 // the API. 12 type ListOpts struct { 13 // ID is the unique identifier for the nic. 14 ID string `json:"port_id"` 15 16 // Status indicates whether a nic is currently operational. 17 Status string `json:"port_state"` 18 } 19 20 // List returns collection of nics. It accepts a ListOpts struct, which allows you to filter and sort 21 // the returned collection for greater efficiency. 22 func List(client *golangsdk.ServiceClient, serverId string, opts ListOpts) ([]Nic, error) { 23 pages, err := pagination.NewPager(client, client.ServiceURL("servers", serverId, "os-interface"), 24 func(r pagination.PageResult) pagination.Page { 25 return NicPage{pagination.LinkedPageBase{PageResult: r}} 26 }).AllPages() 27 if err != nil { 28 return nil, err 29 } 30 31 allNICs, err := ExtractNics(pages) 32 if err != nil { 33 return nil, err 34 } 35 36 return filterNICs(allNICs, opts) 37 } 38 39 // filterNICs used to filter nics using id and status. 40 func filterNICs(nics []Nic, opts ListOpts) ([]Nic, error) { 41 42 var refinedNICs []Nic 43 var matched bool 44 m := map[string]interface{}{} 45 46 if opts.ID != "" { 47 m["ID"] = opts.ID 48 } 49 if opts.Status != "" { 50 m["Status"] = opts.Status 51 } 52 if len(m) > 0 && len(nics) > 0 { 53 for _, nic := range nics { 54 matched = true 55 56 for key, value := range m { 57 if sVal := getStructField(&nic, key); !(sVal == value) { 58 matched = false 59 } 60 } 61 62 if matched { 63 refinedNICs = append(refinedNICs, nic) 64 } 65 } 66 67 } else { 68 refinedNICs = nics 69 } 70 71 return refinedNICs, nil 72 } 73 74 func getStructField(v *Nic, field string) string { 75 r := reflect.ValueOf(v) 76 f := reflect.Indirect(r).FieldByName(field) 77 return f.String() 78 }