-
Notifications
You must be signed in to change notification settings - Fork 81
/
broker.go
46 lines (36 loc) · 924 Bytes
/
broker.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
package broker
import (
"context"
"fmt"
)
type Broker interface {
Name() string
Options() Options
Address() string
Init(...Option) error
Connect() error
Disconnect() error
Publish(ctx context.Context, topic string, msg Any, opts ...PublishOption) error
Subscribe(topic string, handler Handler, binder Binder, opts ...SubscribeOption) (Subscriber, error)
}
func Subscribe[T any](broker Broker, topic string, handler func(context.Context, string, Headers, *T) error, opts ...SubscribeOption) (Subscriber, error) {
return broker.Subscribe(
topic,
func(ctx context.Context, event Event) error {
switch t := event.Message().Body.(type) {
case *T:
if err := handler(ctx, event.Topic(), event.Message().Headers, t); err != nil {
return err
}
default:
return fmt.Errorf("unsupported type: %T", t)
}
return nil
},
func() Any {
var t T
return &t
},
opts...,
)
}