natsio/server_reqres.go

52 lines
1.3 KiB
Go
Raw Normal View History

2021-12-02 03:29:52 +00:00
package natsio
import (
"errors"
"fmt"
2022-08-19 07:07:14 +00:00
"log"
2021-12-02 03:29:52 +00:00
"time"
"github.com/nats-io/nats.go"
)
// Default timeout 10s
const requestTimeout = 10 * time.Second
// Request ...
func (sv Server) Request(subject string, payload []byte) (*nats.Msg, error) {
timeout := requestTimeout
if sv.Config.RequestTimeout > 0 {
timeout = sv.Config.RequestTimeout
}
2022-08-30 08:55:20 +00:00
msg, err := sv.instance.Request(subject, payload, timeout)
if errors.Is(err, nats.ErrNoResponders) {
log.Printf("[NATS SERVER]: request - no responders for subject: %s", subject)
}
return msg, err
2021-12-02 03:29:52 +00:00
}
// Reply ...
func (sv Server) Reply(msg *nats.Msg, payload []byte) error {
2022-04-12 10:39:27 +00:00
return sv.instance.Publish(msg.Reply, payload)
2021-12-02 03:29:52 +00:00
}
// Subscribe ...
func (sv Server) Subscribe(subject string, cb nats.MsgHandler) (*nats.Subscription, error) {
sub, err := sv.instance.Subscribe(subject, cb)
if err != nil {
msg := fmt.Sprintf("[NATS SERVER] - subscribe subject %s error: %s", subject, err.Error())
return nil, errors.New(msg)
}
return sub, nil
}
2022-08-10 10:52:00 +00:00
// NewJSONEncodedConn ...
2022-08-19 07:07:14 +00:00
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
2022-08-10 10:52:00 +00:00
}