Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to set SNS Message Attributes via context #235

Merged
merged 2 commits into from
Nov 5, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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