diff --git a/cluster/options.go b/cluster/options.go index 21896d40a3..d59dc74886 100644 --- a/cluster/options.go +++ b/cluster/options.go @@ -1,6 +1,7 @@ package cluster import ( + "net" "os" "strconv" "strings" @@ -49,3 +50,11 @@ func (do DriverOpts) Float(key, env string) (float64, bool) { } return 0.0, false } + +// IP returns an IP address from the driver options +func (do DriverOpts) IP(key, env string) (net.IP, bool) { + if value, ok := do.String(key, env); ok { + return net.ParseIP(value), true + } + return nil, false +} diff --git a/cluster/options_test.go b/cluster/options_test.go index c15e5cccb6..7ca0653ce2 100644 --- a/cluster/options_test.go +++ b/cluster/options_test.go @@ -1,13 +1,14 @@ package cluster import ( + "net" "os" "testing" "github.com/stretchr/testify/assert" ) -var opts = DriverOpts{"foo1=bar", "foo2=-5", "foo3=7", "foo4=0.6"} +var opts = DriverOpts{"foo1=bar", "foo2=-5", "foo3=7", "foo4=0.6", "foo5=127.0.0.1"} func TestString(t *testing.T) { os.Setenv("FOO_4", "bar") @@ -125,3 +126,20 @@ func TestFloat(t *testing.T) { assert.False(t, ok) assert.Equal(t, val, 0.0) } + +func TestIP(t *testing.T) { + os.Setenv("FOO_4", "0.0.0.0") + defer os.Setenv("FOO_4", "") + + val, ok := opts.IP("foo5", "") + assert.True(t, ok) + assert.Equal(t, val, net.ParseIP("127.0.0.1")) + + val, ok = opts.IP("", "FOO_4") + assert.True(t, ok) + assert.Equal(t, val, net.ParseIP("0.0.0.0")) + + val, ok = opts.IP("invalid", "") + assert.False(t, ok) + assert.Equal(t, val, net.IP(nil)) +}