From 0eb670a0c5aecd3e4c2ebab8ab30a137fb44fdb2 Mon Sep 17 00:00:00 2001 From: Sinh Date: Fri, 19 Aug 2022 14:07:14 +0700 Subject: [PATCH] update json encoder --- json_encoder.go | 26 ++++++++++++++++++++++++++ server_reqres.go | 10 ++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 json_encoder.go diff --git a/json_encoder.go b/json_encoder.go new file mode 100644 index 0000000..379b408 --- /dev/null +++ b/json_encoder.go @@ -0,0 +1,26 @@ +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) + } + return sub, err +} + +// Publish ... +func (e JSONEncoder) Publish(reply string, data interface{}) error { + return e.encConn.Publish(reply, data) +} diff --git a/server_reqres.go b/server_reqres.go index c21b4dc..841f9ef 100644 --- a/server_reqres.go +++ b/server_reqres.go @@ -3,6 +3,7 @@ package natsio import ( "errors" "fmt" + "log" "time" "github.com/nats-io/nats.go" @@ -36,6 +37,11 @@ func (sv Server) Subscribe(subject string, cb nats.MsgHandler) (*nats.Subscripti } // NewJSONEncodedConn ... -func (sv Server) NewJSONEncodedConn() (*nats.EncodedConn, error) { - return nats.NewEncodedConn(sv.instance, nats.JSON_ENCODER) +func (sv Server) NewJSONEncodedConn() (*JSONEncoder, error) { + enc, err := nats.NewEncodedConn(sv.instance, nats.JSON_ENCODER) + if err != nil { + log.Printf("natsio.NewJSONEncodedConn: err %v\n", err) + return nil, err + } + return &JSONEncoder{encConn: enc}, nil }