Skip to content

Commit 46814bf

Browse files
authored
Merge pull request #19 from hadican/ignore-self
feat: ignore self if set true
2 parents 35ab52f + 1025cf0 commit 46814bf

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

Diff for: watcher.go

+10-1
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,16 @@ func (w *Watcher) subscribe() {
226226
default:
227227
}
228228
data := msg.Payload
229-
w.callback(data)
229+
msgStruct := &MSG{}
230+
err := msgStruct.UnmarshalBinary([]byte(data))
231+
if err != nil {
232+
log.Println(fmt.Printf("Failed to parse message: %s with error: %s\n", data, err.Error()))
233+
} else {
234+
isSelf := msgStruct.ID == w.options.LocalID
235+
if !(w.options.IgnoreSelf && isSelf) {
236+
w.callback(data)
237+
}
238+
}
230239
}
231240
}()
232241
wg.Wait()

Diff for: watcher_test.go

+20-2
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ import (
1212
"github.com/casbin/casbin/v2"
1313
)
1414

15-
func initWatcher(t *testing.T) (*casbin.Enforcer, *Watcher) {
16-
w, err := NewWatcher("127.0.0.1:6379", WatcherOptions{})
15+
func initWatcherWithOptions(t *testing.T, wo WatcherOptions) (*casbin.Enforcer, *Watcher) {
16+
w, err := NewWatcher("127.0.0.1:6379", wo)
1717
if err != nil {
1818
t.Fatalf("Failed to connect to Redis: %v", err)
1919
}
@@ -25,6 +25,11 @@ func initWatcher(t *testing.T) (*casbin.Enforcer, *Watcher) {
2525
_ = e.SetWatcher(w)
2626
return e, w.(*Watcher)
2727
}
28+
29+
func initWatcher(t *testing.T) (*casbin.Enforcer, *Watcher) {
30+
return initWatcherWithOptions(t, WatcherOptions{})
31+
}
32+
2833
func TestWatcher(t *testing.T) {
2934
_, w := initWatcher(t)
3035
_ = w.SetUpdateCallback(func(s string) {
@@ -35,6 +40,19 @@ func TestWatcher(t *testing.T) {
3540
time.Sleep(time.Millisecond * 500)
3641
}
3742

43+
func TestWatcherWithIgnoreSelfTrue(t *testing.T) {
44+
wo := WatcherOptions{
45+
IgnoreSelf: true,
46+
OptionalUpdateCallback: func(s string) {
47+
t.Fatalf("This callback should not be called when IgnoreSelf is set true.")
48+
},
49+
}
50+
_, w := initWatcherWithOptions(t, wo)
51+
_ = w.Update()
52+
w.Close()
53+
time.Sleep(time.Millisecond * 500)
54+
}
55+
3856
func TestUpdate(t *testing.T) {
3957
_, w := initWatcher(t)
4058
_ = w.SetUpdateCallback(func(s string) {

0 commit comments

Comments
 (0)