netboxapi/ipam.go

110 lines
2.9 KiB
Go

package netboxapi
import (
"context"
e "git.stinnesbeck.com/nils/errorhandler"
"github.com/netbox-community/go-netbox/v3/netbox/client/ipam"
"github.com/netbox-community/go-netbox/v3/netbox/models"
)
// GetPrefixes returns prefixes from the api filtered by the parameter list param
func (nb NetBoxAPI) GetPrefixes(param ipam.IpamPrefixesListParams) ([]*models.Prefix, error) {
// check if context was set, if not set background
if param.Context == nil {
param.Context = context.Background()
}
var defaultOffset int64
var defaultLimit int64 = 50
// set Offset if not set before
if param.Limit == nil {
param.Limit = &defaultLimit
}
// set Offset if not set before
if param.Offset == nil {
param.Offset = &defaultOffset
}
// get prefixes
prefixes, err := nb.API.Ipam.IpamPrefixesList(&param, nil)
if err != nil {
return nil, e.FormatError("can't get prefixes", err)
}
// variable to hold all prefixes to return
var prefixesToReturn []*models.Prefix
// append first page of models
prefixesToReturn = append(prefixesToReturn, prefixes.Payload.Results...)
// check if there are more prefixes on other pages
if prefixes.Payload.Next != nil {
// there are more pages to get
// calculate new offset
newOffset := *param.Offset + *param.Limit
// set new offset
param.Offset = &newOffset
// get prefixes from next page
nextPagePrefixes, err := nb.GetPrefixes(param)
if err != nil {
return nil, e.FormatError("can't get prefixes", err)
}
// append the results from next page to our prefixes to return
prefixesToReturn = append(prefixesToReturn, nextPagePrefixes...)
}
return prefixesToReturn, nil
}
// GetIPAddresses returns IP addresses from the api filtered by the parameter list param
func (nb NetBoxAPI) GetIPAddresses(param ipam.IpamIPAddressesListParams) ([]*models.IPAddress, error) {
// check if context was set, if not set background
if param.Context == nil {
param.Context = context.Background()
}
var defaultOffset int64
var defaultLimit int64 = 50
// set Offset if not set before
if param.Limit == nil {
param.Limit = &defaultLimit
}
// set Offset if not set before
if param.Offset == nil {
param.Offset = &defaultOffset
}
// get addresses
addresses, err := nb.API.Ipam.IpamIPAddressesList(&param, nil)
if err != nil {
return nil, e.FormatError("can't get prefixes", err)
}
// check if there are no more prefixes on other pages
if addresses.Payload.Next == nil {
// return the results of the first batch, there are no others!
return addresses.Payload.Results, nil
}
// variable to hold all prefixes to return
var addressesToReturn []*models.IPAddress
if err := nb.handlePagination(addresses.Payload.Next.String(), &addressesToReturn); err != nil {
return nil, e.FormatError("can't handle Pagination", err)
}
// append append first batch to the other batches
addressesToReturn = append(addressesToReturn, addresses.Payload.Results...)
// return all addresses
return addressesToReturn, nil
}