Skip to content
Snippets Groups Projects
Commit ed36be41 authored by Dave Cameron's avatar Dave Cameron
Browse files

Helper functions for most common configurations.

parent c01d6b1e
No related branches found
No related tags found
No related merge requests found
generate: generate:
swagger generate client --target=./netbox --spec=./swagger.json --copyright-file=./copyright_header.txt swagger generate client --target=./netbox --spec=./swagger.json --copyright-file=./copyright_header.txt
clean: clean:
rm -rf netbox/* rm -rf netbox/client netbox/models
integration:
go test ./... -tags=integration
...@@ -9,43 +9,36 @@ This package assumes you are using NetBox 2.0, as the NetBox 1.0 API no longer e ...@@ -9,43 +9,36 @@ This package assumes you are using NetBox 2.0, as the NetBox 1.0 API no longer e
Using the client Using the client
================ ================
The `github.com/go-netbox/netbox/client` package is the entry point for using the client. By default, the client will The `github.com/go-netbox/netbox` package has some convenience functions for creating clients with the most common
connect to an api at `http://localhost:8000/api`. The simplest possible usage looks like: configurations you are likely to need while connecting to NetBox. `NewNetboxAt` allows you to specify a hostname
(including port, if you need it), and `NewNetboxWithAPIKey` allows you to specify both a hostname:port and API token.
```golang ```golang
// Passing nil to this method results in all default values import (
c := client.NewHTTPClient(nil) "github.com/digitalocean/go-netbox/netbox"
)
... work with the returned client ... ...
c := netbox.NewNetboxAt("your.netbox.host:8000")
// OR
c := netbox.NewNetboxWithAPIKey("your.netbox.host:8000", "your_netbox_token")
``` ```
A more likely scenario is to connect to a remote netbox: If you specify the API key, you do not need to pass an additional `authInfo` to operations that need authentication, and
can pass `nil`:
```golang ```golang
t := client.DefaultTransportConfig().WithHost("your.netbox.host") c.Dcim.DcimDeviceTypesCreate(createRequest, nil)
c := client.NewHTTPClientWithConfig(nil, t)
``` ```
The client is generated using [go-swagger](https://github.com/go-swagger/go-swagger). This means the generated client More complex client configuration
makes use of [github.com/go-openapi/runtime/client](https://godoc.org/github.com/go-openapi/runtime/client). The [godocs =================================
for that module](https://godoc.org/github.com/go-openapi/runtime/client) explain the client options in detail, including
different authentication and debugging options.
Setting the debug flag will print all requests and responses on standard out, which is great for debugging unexpected The client is generated using [go-swagger](https://github.com/go-swagger/go-swagger). This means the generated client
results. It does require creating the client in the lower level `go-openapi` libraries: makes use of [github.com/go-openapi/runtime/client](https://godoc.org/github.com/go-openapi/runtime/client). If you need
```golang a more complex configuration, it is probably possible with a combination of this generated client and the runtime
import ( options.
"github.com/digitalocean/go-netbox/netbox/client"
"github.com/go-openapi/strfmt"
runtimeclient "github.com/go-openapi/runtime/client"
)
func main() {
t := runtimeclient.New(client.DefaultHost, client.DefaultBasePath, client.DefaultSchemes)
t.SetDebug(true)
c := client.New(t, strfmt.Default)
... work with c ... The [godocs for the go-openapi/runtime/client module](https://godoc.org/github.com/go-openapi/runtime/client) explain
) the client options in detail, including different authentication and debugging options. One thing I want to flag because
``` it is so useful: setting the `DEBUG` environment variable will dump all requests to standard out.
Regenerating the client Regenerating the client
======================= =======================
......
// Copyright 2018 The go-netbox Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"os"
"github.com/digitalocean/go-netbox/netbox/client"
)
func main() {
c := defaultClient()
rs, err := c.Dcim.DcimRacksList(nil, nil)
if err != nil {
fmt.Printf("%v\n", err)
os.Exit(1)
}
fmt.Printf("%v\n", *(rs.Payload.Count))
}
func defaultClient() *client.NetBox {
// Passing nil to this method results in all default configuration for the client.
// That is, a client that connects to http://localhost:8000, and using default
// field formats. (e.g. remove '-' from json field names)
return client.NewHTTPClient(nil)
}
\ No newline at end of file
package netbox
import (
"fmt"
"github.com/go-openapi/strfmt"
runtimeclient "github.com/go-openapi/runtime/client"
"github.com/digitalocean/go-netbox/netbox/client"
)
func NewNetboxAt(host string) *client.NetBox {
t := client.DefaultTransportConfig().WithHost(host)
return client.NewHTTPClientWithConfig(strfmt.Default, t)
}
const authHeaderName = "Authorization"
const authHeaderFormat = "Token %v"
func NewNetboxWithAPIKey(host string, apiToken string) *client.NetBox {
t := runtimeclient.New(host, client.DefaultBasePath, client.DefaultSchemes)
t.DefaultAuthentication = runtimeclient.APIKeyAuth(authHeaderName, "header", fmt.Sprintf(authHeaderFormat, apiToken))
return client.New(t, strfmt.Default)
}
...@@ -14,16 +14,14 @@ ...@@ -14,16 +14,14 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
package main package netbox
import ( import (
"testing" "testing"
"fmt"
"github.com/digitalocean/go-netbox/netbox/client/dcim" "github.com/digitalocean/go-netbox/netbox/client/dcim"
"github.com/digitalocean/go-netbox/netbox/models" "github.com/digitalocean/go-netbox/netbox/models"
"github.com/go-openapi/strfmt" "github.com/go-openapi/strfmt"
"github.com/go-openapi/runtime"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
...@@ -33,7 +31,7 @@ import ( ...@@ -33,7 +31,7 @@ import (
// python3 netbox/manage.py runserver 0.0.0.0:8000 --insecure // python3 netbox/manage.py runserver 0.0.0.0:8000 --insecure
func TestRetrieveDeviceList(t *testing.T) { func TestRetrieveDeviceList(t *testing.T) {
c := defaultClient() c := NewNetboxAt("localhost:8000")
list, err := c.Dcim.DcimDevicesList(nil, nil) list, err := c.Dcim.DcimDevicesList(nil, nil)
...@@ -42,7 +40,7 @@ func TestRetrieveDeviceList(t *testing.T) { ...@@ -42,7 +40,7 @@ func TestRetrieveDeviceList(t *testing.T) {
} }
func TestSubdeviceRole(t *testing.T) { func TestSubdeviceRole(t *testing.T) {
c := defaultClient() c := NewNetboxWithAPIKey("localhost:8000", "7b4e1ceaaf93528a41e64d048090f7fe13ed16f4")
role := true role := true
manufacturerID := int64(1) manufacturerID := int64(1)
...@@ -59,7 +57,7 @@ func TestSubdeviceRole(t *testing.T) { ...@@ -59,7 +57,7 @@ func TestSubdeviceRole(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
createRequest := dcim.NewDcimDeviceTypesCreateParams().WithData(newDeviceType) createRequest := dcim.NewDcimDeviceTypesCreateParams().WithData(newDeviceType)
createResponse, err := c.Dcim.DcimDeviceTypesCreate(createRequest, runtime.ClientAuthInfoWriterFunc(SetAuthenticationHeader)) createResponse, err := c.Dcim.DcimDeviceTypesCreate(createRequest, nil)
assert.NoError(t, err) assert.NoError(t, err)
newID := float64(createResponse.Payload.ID) newID := float64(createResponse.Payload.ID)
...@@ -71,13 +69,6 @@ func TestSubdeviceRole(t *testing.T) { ...@@ -71,13 +69,6 @@ func TestSubdeviceRole(t *testing.T) {
assert.EqualValues(t, "Test device type", retrieveResponse.Payload.Results[0].Comments) assert.EqualValues(t, "Test device type", retrieveResponse.Payload.Results[0].Comments)
deleteRequest := dcim.NewDcimDeviceTypesDeleteParams().WithID(int64(newID)) deleteRequest := dcim.NewDcimDeviceTypesDeleteParams().WithID(int64(newID))
_, err = c.Dcim.DcimDeviceTypesDelete(deleteRequest, runtime.ClientAuthInfoWriterFunc(SetAuthenticationHeader)) _, err = c.Dcim.DcimDeviceTypesDelete(deleteRequest, nil)
assert.NoError(t, err) assert.NoError(t, err)
} }
const apiToken = "7b4e1ceaaf93528a41e64d048090f7fe13ed16f4"
const authHeaderFormat = "Token %v"
func SetAuthenticationHeader(req runtime.ClientRequest, _ strfmt.Registry) error {
req.SetHeaderParam("Authorization", fmt.Sprintf(authHeaderFormat, apiToken))
return nil
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment