-
Notifications
You must be signed in to change notification settings - Fork 11
/
client_unsubscribe.go
59 lines (47 loc) · 1.52 KB
/
client_unsubscribe.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package courier
import (
"context"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
// Unsubscribe removes any subscription to messages from an MQTT broker
func (c *Client) Unsubscribe(ctx context.Context, topics ...string) error {
if err := c.unsubscriber.Unsubscribe(ctx, topics...); err != nil {
return err
}
c.subMu.Lock()
for _, topic := range topics {
delete(c.subscriptions, topic)
}
c.subMu.Unlock()
return nil
}
// UseUnsubscriberMiddleware appends a UnsubscriberMiddlewareFunc to the chain.
// Middleware can be used to intercept or otherwise modify, process or skip subscriptions.
// They are executed in the order that they are applied to the Client.
func (c *Client) UseUnsubscriberMiddleware(mwf ...UnsubscriberMiddlewareFunc) {
for _, fn := range mwf {
c.usMiddlewares = append(c.usMiddlewares, fn)
}
c.unsubscriber = unsubscriberHandler(c)
for i := len(c.usMiddlewares) - 1; i >= 0; i-- {
c.unsubscriber = c.usMiddlewares[i].Middleware(c.unsubscriber)
}
}
func unsubscriberHandler(c *Client) Unsubscriber {
return UnsubscriberFunc(func(ctx context.Context, topics ...string) error {
return c.execute(func(cc mqtt.Client) error {
return c.handleToken(ctx, cc.Unsubscribe(topics...), ErrUnsubscribeTimeout)
}, removeSubsFromState(topics...))
})
}
func removeSubsFromState(topics ...string) execOptWithState {
return func(f func(mqtt.Client) error, s *internalState) error {
s.mu.Lock()
defer s.mu.Unlock()
err := f(s.client)
if err == nil {
s.subsCalled.Delete(topics...)
}
return err
}
}