-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
53 lines (47 loc) · 1.48 KB
/
client.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
package line
import (
"fmt"
"github.com/lorestudios/line/protocol"
"github.com/nats-io/nats.go"
"github.com/sandertv/gophertunnel/minecraft/protocol/packet"
"time"
)
// Client represents a client that can handle packets coming to it and write packets in response.
type Client struct {
*Consumer
}
// NewClient returns a new Client ready to use with the required data.
func NewClient(l *Line, subject, queue string, handlers *protocol.Handlers) *Client {
return &Client{
Consumer: NewConsumer(l, subject, queue, handlers),
}
}
// Send sends a packet to the given subject without waiting for a response.
func (c *Client) Send(subject string, pk packet.Packet) error {
data, err := c.line.WritePacket(pk)
if err != nil {
return err
}
return c.line.Conn().Publish(subject, data)
}
// Request sends a request packet to the given subject and awaits a response. The response and any errors are returned.
func (c *Client) Request(subject string, pk packet.Packet) (packet.Packet, error) {
data, err := c.line.WritePacket(pk)
if err != nil {
return nil, err
}
m, err := c.line.Conn().Request(subject, data, time.Second*5)
if err != nil {
return nil, fmt.Errorf("no response received from poet: %v", err)
}
p, err := c.line.ReadPacket(m.Data)
return p, err
}
// Reply sends a response to a request packet. Any errors are returned.
func (c *Client) Reply(msg *nats.Msg, pk packet.Packet) error {
data, err := c.line.WritePacket(pk)
if err != nil {
return err
}
return msg.Respond(data)
}