Skip to content

Commit 2a8cd77

Browse files
authored
Merge pull request #3 from digitalocean/prepend-base-path
client{,_test}: allow base URL path to be specified and prepended to …
2 parents a06f2c7 + 3977c33 commit 2a8cd77

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

client.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"encoding/json"
1919
"net/http"
2020
"net/url"
21+
"path"
2122
)
2223

2324
// A Client is a NetBox client. It can be used to retrieve network and
@@ -69,6 +70,16 @@ func (c *Client) newRequest(method string, endpoint string, options valuer) (*ht
6970
if err != nil {
7071
return nil, err
7172
}
73+
74+
// Allow specifying a base path for API requests, so if a NetBox server
75+
// resides at a path like http://example.com/netbox/, API requests will
76+
// be sent to http://example.com/netbox/api/...
77+
//
78+
// Enables support of: https://github.com/digitalocean/netbox/issues/212.
79+
if c.u.Path != "" {
80+
rel.Path = path.Join(c.u.Path, rel.Path)
81+
}
82+
7283
u := c.u.ResolveReference(rel)
7384

7485
// If no valuer specified, create a request with no query parameters

client_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,28 @@ func TestClientQueryParameters(t *testing.T) {
8080
}
8181
}
8282

83+
func TestClientPrependBaseURLPath(t *testing.T) {
84+
u, err := url.Parse("http://example.com/netbox/")
85+
if err != nil {
86+
t.Fatalf("unexpected error: %v", err)
87+
}
88+
89+
c := &Client{
90+
u: u,
91+
client: &http.Client{},
92+
}
93+
94+
req, err := c.newRequest(http.MethodGet, "/api/ipam/vlans", nil)
95+
if err != nil {
96+
t.Fatal("expected an error, but no error returned")
97+
}
98+
99+
if want, got := "/netbox/api/ipam/vlans", req.URL.Path; want != got {
100+
t.Fatalf("unexpected URL path:\n- want: %q\n- got: %q",
101+
want, got)
102+
}
103+
}
104+
83105
type testValuer struct {
84106
Foo string
85107
Bar int

0 commit comments

Comments
 (0)