无法在GO中解组AWS SQS消息

时间:2019-06-21 18:50:04

标签: go amazon-sqs

伙计,

我正在尝试从SQS FIFO队列中解封消息,并且正在获取

cannot unmarshal array into Go struct field SendMessageInput.MessageAttributes of type map[string]*sqs.MessageAttributeValue
// unmarshal for the sqs message
var publishedMessage sqs.SendMessageInput
if err := json.Unmarshal([]byte(*msg.Body), &publishedMessage); err != nil {
  onError(err)
  continue
}

// unmarhsal for the message sent
var result Message
if err := json.Unmarshal([]byte(*publishedMessage.MessageBody), &result); err != nil {
    onError(err)
    continue
}

当我通过SQS控制台查看消息时,消息本身看起来还可以。

这是消息中的示例messageAttributes部分:

"messageAttributes":[{"name":"foo","dataType":"String","attributeValue":"something"},{"name":"uid","dataType":"String","attributeValue":"26799e9c-9455-11e9-bc42-526af7764f64"}]

从SDK文档中:

// Each message attribute consists of a Name, Type, and Value. For more information,
    // see Amazon SQS Message Attributes (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-attributes.html)
    // in the Amazon Simple Queue Service Developer Guide.
    MessageAttributes map[string]*MessageAttributeValue `locationName:"MessageAttribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"`

我在这儿做错什么?

1 个答案:

答案 0 :(得分:3)

对于那些偶然发现这个问题的人...

// Message encapsulates all the information to publish in a message
type Message struct {
    Body              json.RawMessage            `json:"body"`
    Headers           map[string]json.RawMessage `json:"headers"`
    Environment       string                     `json:"env"`
    PublishTime       int64                      `json:"publishTime"`
    MessageAttributes []Attributes               `json:"messageAttributes"`
}

for _, msg := range resp.Messages {

  var result Message
  if err := json.Unmarshal([]byte(*msg.Body), &result); err != nil {
    onError(err)
    continue
  }

  metadata := &Metadata{
    ReceiptHandle: *msg.ReceiptHandle,
    MD5OfBody:     *msg.MD5OfBody,
    SQSMessageID:  *msg.MessageId,
    ReceiveCount:  *msg.Attributes[sqs.MessageSystemAttributeNameApproximateReceiveCount],
  }

  onMessage(result, *metadata)

}