Skip to content

Update connection structs to avoid read only warning from server #57

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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))

Expand Down
8 changes: 8 additions & 0 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
17 changes: 17 additions & 0 deletions util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}