-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdot_nats.go
50 lines (42 loc) · 942 Bytes
/
dot_nats.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
package xtemplate
import (
"context"
"fmt"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)
type DotNats struct {
ctx context.Context
*nats.Conn
jetstream.JetStream
}
func (d *DotNats) Subscribe(subject string) (<-chan *nats.Msg, error) {
ch := make(chan *nats.Msg)
sub, err := d.Conn.ChanSubscribe(subject, ch)
if err != nil {
return nil, err
}
done := d.ctx.Done()
go func() {
<-done
sub.Unsubscribe()
close(ch)
}()
return ch, nil
}
func (d *DotNats) Publish(subject, message string) error {
return d.Conn.Publish(subject, []byte(message))
}
func (d *DotNats) Request(subject, data string, timeout_ ...time.Duration) (*nats.Msg, error) {
var timeout time.Duration
switch len(timeout_) {
case 0:
timeout = 5 * time.Second
case 1:
timeout = timeout_[0]
default:
return nil, fmt.Errorf("too many timeout args")
}
return d.Conn.Request(subject, []byte(data), timeout)
}