Skip to content

Commit

Permalink
fix: nats publisher func to encode req
Browse files Browse the repository at this point in the history
  • Loading branch information
ayushkedia29 committed Mar 27, 2024
1 parent fe6d078 commit 95be4b4
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions transport/nats/publisher_fn.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
package nats

import (
"bytes"
"context"
"encoding/json"

"github.com/nats-io/nats.go"
natn "github.com/nats-io/nats.go"
"github.com/unbxd/go-base/v2/errors"
)

// EncodeJSONRequest is an Encoder that serializes the request as a
// JSON object to the Data of the Msg. Many JSON-over-NATS services can use it as
// a sensible default.
func EncodeJSONRequest(_ context.Context, msg *natn.Msg, request interface{}) error {
b, err := json.Marshal(request)
func EncodeJSONRequest(_ context.Context, subject string, request interface{}) (*nats.Msg, error) {
var (
buf bytes.Buffer
err error
)

err = json.NewEncoder(&buf).Encode(request)
if err != nil {
return err
return nil, errors.Wrap(err, "defaultencoder: encoding error")
}

msg.Data = b

return nil
return &natn.Msg{
Subject: subject,
Data: buf.Bytes(),
}, err
}

0 comments on commit 95be4b4

Please sign in to comment.