github.com/huaweicloud/golangsdk@v0.0.0-20210831081626-d823fe11ceba/openstack/bms/v2/nics/requests.go (about) 1 package nics 2 3 import ( 4 "reflect" 5 6 "github.com/huaweicloud/golangsdk" 7 "github.com/huaweicloud/golangsdk/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 or not 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(c *golangsdk.ServiceClient, serverId string, opts ListOpts) ([]Nic, error) { 23 u := listURL(c, serverId) 24 pages, err := pagination.NewPager(c, u, 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 string(f.String()) 78 } 79 80 // Get retrieves a particular nic based on its unique ID. 81 func Get(c *golangsdk.ServiceClient, serverId string, id string) (r GetResult) { 82 _, r.Err = c.Get(getURL(c, serverId, id), &r.Body, nil) 83 return 84 }