netboxapi/main.go

91 lines
2.5 KiB
Go
Raw Normal View History

2023-03-26 07:40:04 +00:00
// Package netboxapi provides custom functions for the default
// go-netbox package. It mostly handles pagination.
2023-03-26 07:33:41 +00:00
package netboxapi
import (
"context"
"fmt"
e "git.stinnesbeck.com/nils/errorhandler"
transport "github.com/go-openapi/runtime/client"
"github.com/netbox-community/go-netbox/v3/netbox/client"
"github.com/netbox-community/go-netbox/v3/netbox/client/ipam"
"github.com/netbox-community/go-netbox/v3/netbox/models"
)
// NetBoxAPI is the type we use to add custom functions
type NetBoxAPI client.NetBoxAPI
// NewNetBoxClient returns a client to NetBox at the given url,
// using the provided token
func NewNetBoxClient(token string, url string) (NetBoxAPI, error) {
// Construct the API basis and configure authentication
t := transport.New(url, client.DefaultBasePath, []string{"https"})
t.DefaultAuthentication = transport.APIKeyAuth(
"Authorization",
"header",
fmt.Sprintf("Token %v", token),
)
// create NetBox api variable
n := client.New(t, nil)
// create a new variable for our custom functions
var nb NetBoxAPI = NetBoxAPI(*n)
return nb, nil
}
// 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.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
}