diff --git a/device_roles.go b/device_roles.go new file mode 100644 index 0000000..f5013f9 --- /dev/null +++ b/device_roles.go @@ -0,0 +1,102 @@ +package netboxgo + +import ( + "crypto/tls" + "encoding/json" + "io/ioutil" + "net/http" + "net/url" + "time" + + "github.com/gorilla/schema" + "github.com/pkg/errors" +) + +type ListDeviceRoles struct { + Count int `json:"count"` + Next string `json:"next"` + Previous string `json:"previous"` + Results []DeviceRole `json:"results"` +} + +type DeviceRole struct { + ID int `json:"id"` + URL string `json:"url"` + Name string `json:"name"` + Slug string `json:"slug"` + Color string `json:"color"` + VMRole bool `json:"vm_role"` + Description string `json:"description"` + DeviceCount int `json:"device_count"` + VirtualmachineCount int `json:"virtualmachine_count"` +} + +// DeviceTypeFilter is used to filter dcim_device_roles query to the Netbox API +type DeviceRoleFilter struct { + Offset int64 `schema:"offset,omitempty"` + Limit int64 `schema:"limit,omitempty"` + + // User specific filters + ID string `schema:"id,omitempty"` + Name string `schema:"name,omitempty"` + Slug string `schema:"slug,omitempty"` + Color string `schema:"color,omitempty"` + VMRole string `schema:"vm_role,omitempty"` + Q string `schema:"q,omitempty"` +} + +// ListDeviceTypes method returns dcim_device_roles from Netbox API +func (n *NetBox) ListDeviceRoles(d *ListDeviceRoles, f *DeviceRoleFilter) error { + encoder := schema.NewEncoder() + + transport := &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: n.InsecureSkipVerify}, + } + timeout := time.Duration(60 * time.Second) + client := &http.Client{ + Timeout: timeout, + Transport: transport, + } + deviceurl := n.RootURL + "/api/dcim/device-roles/" + if f != nil { + form := url.Values{} + err := encoder.Encode(f, form) + if err != nil { + return err + } + query := form.Encode() + deviceurl = deviceurl + "?" + query + } + var request *http.Request + var err error + request, err = http.NewRequest("GET", deviceurl, nil) + if err != nil { + return err + } + request.Header.Add("Accept", "application/json") + request.Header.Add("Authorization", " Token "+n.Token) + response, err := client.Do(request) + if err != nil { + return err + } + + if response.StatusCode != http.StatusOK { + return errors.Errorf("Error: response was: %d should be %d (%s)\n", response.StatusCode, http.StatusOK, deviceurl) + } + + data, err := ioutil.ReadAll(response.Body) + if err != nil { + return err + } + + err = response.Body.Close() + if err != nil { + return err + } + + err = json.Unmarshal(data, &d) + if err != nil { + return err + } + return nil +}