From ef52e7b8204a3a36274d2f7bf6f0aac26379da19 Mon Sep 17 00:00:00 2001 From: QuanTT0110 Date: Thu, 11 May 2023 16:00:05 +0700 Subject: [PATCH] update json encoder --- json_encoder.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 json_encoder.go diff --git a/json_encoder.go b/json_encoder.go new file mode 100644 index 0000000..c0bde64 --- /dev/null +++ b/json_encoder.go @@ -0,0 +1,44 @@ +package natsio + +import ( + "log" + + "github.com/nats-io/nats.go" +) + +// JSONEncoder ... +type JSONEncoder struct { + encConn *nats.EncodedConn +} + +// Subscribe ... +func (e JSONEncoder) Subscribe(subject string, cb nats.Handler) (*nats.Subscription, error) { + sub, err := e.encConn.Subscribe(subject, cb) + if err != nil { + log.Printf("natsio.JSONEncoder.Subscribe err: %v\n", err) + } else { + log.Printf("natsio.JSONEncoder - subscribed to subject %s successfully\n", subject) + } + return sub, err +} + +// QueueSubscribe ... +func (e JSONEncoder) QueueSubscribe(subject, queue string, cb nats.Handler) (*nats.Subscription, error) { + sub, err := e.encConn.QueueSubscribe(subject, queue, cb) + if err != nil { + log.Printf("natsio.JSONEncoder.QueueSubscribe err: %v\n", err) + } else { + log.Printf("natsio.JSONEncoder.QueueSubscribe - subscribed to subject %s successfully\n", subject) + } + return sub, err +} + +// Publish ... +func (e JSONEncoder) Publish(reply string, data interface{}) error { + return e.encConn.Publish(reply, data) +} + +// Request ... +func (e JSONEncoder) Request(subject string, data interface{}, res interface{}) error { + return e.encConn.Request(subject, data, res, requestTimeout) +}