Skip to content

Commit

Permalink
Allow to set SNS Message Attributes via context (#235)
Browse files Browse the repository at this point in the history
* Allow to set SNS Message Attributes via context

* use private context key as suggested by @jprobinson
  • Loading branch information
taraspos authored and jprobinson committed Nov 5, 2019
1 parent d0e7717 commit 8e8dc8e
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion pubsub/aws/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ import (
"golang.org/x/net/context"
)

// The key type is unexported to prevent collisions with context keys defined in
// other packages.
type key int

// msgAttrsKey is the context key for the SNS Message Attributes. Its value of zero is
// arbitrary. If this package defined other context keys, they would have
// different integer values.
const msgAttrsKey key = 0

// publisher will accept AWS credentials and an SNS topic name
// and it will emit any publish events to it.
type publisher struct {
Expand Down Expand Up @@ -79,17 +88,28 @@ func (p *publisher) Publish(ctx context.Context, key string, m proto.Message) er

// PublishRaw will emit the byte array to the SNS topic.
// The key will be used as the SNS message subject.
func (p *publisher) PublishRaw(_ context.Context, key string, m []byte) error {
// You can use func WithMessageAttributes to set SNS message attributes for the message
func (p *publisher) PublishRaw(ctx context.Context, key string, m []byte) error {
msg := &sns.PublishInput{
TopicArn: &p.topic,
Subject: &key,
Message: aws.String(base64.StdEncoding.EncodeToString(m)),
}

if v, ok := ctx.Value(msgAttrsKey).(map[string]*sns.MessageAttributeValue); ok {
msg.MessageAttributes = v
}

_, err := p.sns.Publish(msg)
return err
}

// WithMessaggeAttributes used to add SNS Message Attributes to the context
// for further usage in publishing messages to sns with provided attributes
func WithMessaggeAttributes(ctx context.Context, msgAttrs map[string]*sns.MessageAttributeValue) context.Context {
return context.WithValue(ctx, msgAttrsKey, msgAttrs)
}

var (
// defaultSQSMaxMessages is default the number of bulk messages
// the subscriber will attempt to fetch on each
Expand Down

0 comments on commit 8e8dc8e

Please sign in to comment.