diff --git a/conn.go b/conn.go index db6d542d..d091a074 100644 --- a/conn.go +++ b/conn.go @@ -73,6 +73,7 @@ type Conn struct { xid uint32 sessionTimeoutMs int32 // session timeout in milliseconds passwd []byte + readOnly bool // accept connection to ZK server in read-only mode, requires ZK 3.4+ dialer Dialer hostProvider HostProvider @@ -193,6 +194,7 @@ func Connect(servers []string, sessionTimeout time.Duration, options ...connOpti eventChan: ec, shouldQuit: make(chan struct{}), connectTimeout: 1 * time.Second, + readOnly: false, sendChan: make(chan *request, sendChanSize), requests: make(map[int32]*request), watchers: make(map[watchPathType][]chan Event), @@ -232,6 +234,13 @@ func WithDialer(dialer Dialer) connOption { } } +// WithReadOnly returns a connection option specifying the usage of ZK servers in readonly mode +func WithReadOnly(readOnly bool) connOption { + return func(c *Conn) { + c.readOnly = readOnly + } +} + // WithHostProvider returns a connection option specifying a non-default HostProvider. func WithHostProvider(hostProvider HostProvider) connOption { return func(c *Conn) { @@ -638,6 +647,8 @@ func (c *Conn) authenticate() error { if err != nil { return err } + n++ + buf = append(buf, boolToByte(c.readOnly)) binary.BigEndian.PutUint32(buf[:4], uint32(n)) diff --git a/util.go b/util.go index 5a92b66b..ebeeb19b 100644 --- a/util.go +++ b/util.go @@ -117,3 +117,11 @@ func validatePath(path string, isSequential bool) error { } return nil } + +// boolToByte transforms true in 1, false in 0 +func boolToByte(b bool) byte { + if b { + return 1 + } + return 0 +} diff --git a/util_test.go b/util_test.go index 53a59505..8340928d 100644 --- a/util_test.go +++ b/util_test.go @@ -51,3 +51,20 @@ func TestValidatePath(t *testing.T) { } } } + +func TestBoolToByte(t *testing.T) { + tt := []struct{ + given bool + expected byte + }{ + {true, 1}, + {false, 0}, + } + + for _, tc := range tt { + result := boolToByte(tc.given) + if result != tc.expected { + t.Errorf("failed to transform bool into byte: %v", tc.given) + } + } +}