diff --git a/api/client.go b/api/client.go index c61fea1b42..f53a70eeb6 100644 --- a/api/client.go +++ b/api/client.go @@ -238,6 +238,13 @@ type Client struct { // automatically added to the client. Otherwise, you must manually call // `SetToken()`. func NewClient(c *Config) (*Client, error) { + if c == nil { + c = DefaultConfig() + if err := c.ReadEnvironment(); err != nil { + return nil, fmt.Errorf("error reading environment: %v", err) + } + } + u, err := url.Parse(c.Address) if err != nil { return nil, err @@ -271,6 +278,18 @@ func NewClient(c *Config) (*Client, error) { return client, nil } +// Sets the address of Vault in the client. The format of address should be +// "://:". Setting this on a client will override the +// value of VAULT_ADDR environment variable. +func (c *Client) SetAddress(addr string) error { + var err error + if c.addr, err = url.Parse(addr); err != nil { + return fmt.Errorf("failed to set address: %v", err) + } + + return nil +} + // SetWrappingLookupFunc sets a lookup function that returns desired wrap TTLs // for a given operation and path func (c *Client) SetWrappingLookupFunc(lookupFunc WrappingLookupFunc) { diff --git a/api/client_test.go b/api/client_test.go index b0deee96ac..f95d795065 100644 --- a/api/client_test.go +++ b/api/client_test.go @@ -36,6 +36,29 @@ func TestDefaultConfig_envvar(t *testing.T) { } } +func TestClientNilConfig(t *testing.T) { + client, err := NewClient(nil) + if err != nil { + t.Fatal(err) + } + if client == nil { + t.Fatal("expected a non-nil client") + } +} + +func TestClientSetAddress(t *testing.T) { + client, err := NewClient(nil) + if err != nil { + t.Fatal(err) + } + if err := client.SetAddress("http://172.168.2.1:8300"); err != nil { + t.Fatal(err) + } + if client.addr.Host != "172.168.2.1:8300" { + t.Fatalf("bad: expected: '172.168.2.1:8300' actual: %q", client.addr.Host) + } +} + func TestClientToken(t *testing.T) { tokenValue := "foo" handler := func(w http.ResponseWriter, req *http.Request) {}