Skip to content

Commit

Permalink
add subscribe and publish topics to message context (#165)
Browse files Browse the repository at this point in the history
  • Loading branch information
eafzali authored and roblaszczak committed Dec 3, 2019
1 parent 6634c70 commit c9213ee
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
10 changes: 10 additions & 0 deletions message/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const (
handlerNameKey ctxKey = "handler_name"
publisherNameKey ctxKey = "publisher_name"
subscriberNameKey ctxKey = "subscriber_name"
subscribeTopicKey ctxKey = "subscribe_topic"
publishTopicKey ctxKey = "publish_topic"
)

func valFromCtx(ctx context.Context, key ctxKey) string {
Expand All @@ -31,3 +33,11 @@ func PublisherNameFromCtx(ctx context.Context) string {
func SubscriberNameFromCtx(ctx context.Context) string {
return valFromCtx(ctx, subscriberNameKey)
}

func SubscribeTopicFromCtx(ctx context.Context) string {
return valFromCtx(ctx, subscribeTopicKey)
}

func PublishTopicFromCtx(ctx context.Context) string {
return valFromCtx(ctx, publishTopicKey)
}
6 changes: 4 additions & 2 deletions message/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ func TestRouter_Context_Stringer(t *testing.T) {
handlerName := "handler_name_stringer_test"
router.AddHandler(
handlerName,
"",
"sub-topic",
sub,
"",
"pub-topic",
pub,
handlerFunc,
)
Expand All @@ -71,6 +71,8 @@ func TestRouter_Context_Stringer(t *testing.T) {
require.Equal(t, handlerName, message.HandlerNameFromCtx(ctx))
require.Equal(t, sub.String(), message.SubscriberNameFromCtx(ctx))
require.Equal(t, pub.String(), message.PublisherNameFromCtx(ctx))
require.Equal(t, "sub-topic", message.SubscribeTopicFromCtx(ctx))
require.Equal(t, "pub-topic", message.PublishTopicFromCtx(ctx))
}

type unnamedMockPublisher struct{}
Expand Down
6 changes: 6 additions & 0 deletions message/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,12 @@ func (h *handler) addHandlerContext(messages ...*Message) {
if h.subscriberName != "" {
ctx = context.WithValue(ctx, subscriberNameKey, h.subscriberName)
}
if h.subscribeTopic != "" {
ctx = context.WithValue(ctx, subscribeTopicKey, h.subscribeTopic)
}
if h.publishTopic != "" {
ctx = context.WithValue(ctx, publishTopicKey, h.publishTopic)
}
messages[i].SetContext(ctx)
}
}
Expand Down

0 comments on commit c9213ee

Please sign in to comment.