From 41eef2a5be3edb3e2fd1db897a08522c00525460 Mon Sep 17 00:00:00 2001 From: "R.I.Pienaar" Date: Mon, 16 Nov 2020 15:52:39 +0100 Subject: [PATCH] ensure response message goes to the reply subject in RespondMsg Signed-off-by: R.I.Pienaar --- nats.go | 1 + nats_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/nats.go b/nats.go index aa4db8347..2728a92d5 100644 --- a/nats.go +++ b/nats.go @@ -3888,6 +3888,7 @@ func (m *Msg) RespondMsg(msg *Msg) error { if m.Reply == "" { return ErrMsgNoReply } + msg.Subject = m.Reply m.Sub.mu.Lock() nc := m.Sub.conn m.Sub.mu.Unlock() diff --git a/nats_test.go b/nats_test.go index 75cfd1b45..951c42de0 100644 --- a/nats_test.go +++ b/nats_test.go @@ -2645,3 +2645,40 @@ func TestJSSubscribe(t *testing.T) { t.Fatalf("subscriber not subscribed to the delivery subject") } } + +func TestMsg_RespondMsg(t *testing.T) { + s := RunServerOnPort(-1) + defer s.Shutdown() + + nc, err := Connect(s.ClientURL()) + if err != nil { + t.Fatalf("Expected to connect to server, got %v", err) + } + defer nc.Close() + + sub, err := nc.SubscribeSync(NewInbox()) + if err != nil { + t.Fatalf("subscribe failed: %s", err) + } + + nc.PublishMsg(&Msg{Reply: sub.Subject, Subject: sub.Subject, Data: []byte("request")}) + req, err := sub.NextMsg(time.Second) + if err != nil { + t.Fatalf("NextMsg failed: %s", err) + } + + // verifies that RespondMsg sets the reply subject on msg based on req + err = req.RespondMsg(&Msg{Data: []byte("response")}) + if err != nil { + t.Fatalf("RespondMsg failed: %s", err) + } + + resp, err := sub.NextMsg(time.Second) + if err != nil { + t.Fatalf("NextMsg failed: %s", err) + } + + if !bytes.Equal(resp.Data, []byte("response")) { + t.Fatalf("did not get correct response: %q", resp.Data) + } +}