【问题标题】:Unable to unmarshal AWS SQS message in GO无法在 GO 中解组 AWS SQS 消息
【发布时间】:2019-06-22 03:45:19
【问题描述】:

伙计们,

我正在尝试从 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"`

伙计们,我做错了什么?

【问题讨论】:

  • 如果他们的 SDK 将字段定义为地图,但他们的 API 为该值返回了一个 json 数组,那么问题似乎出在他们的 SDK 或 API 上,因为它们彼此不一致。
  • ... 如果是这种情况,那么您可以通过首先解组为与 json 匹配的自定义类型来解决此问题,然后如果需要,您可以将其转换为 SDK 类型手动。
  • 100%。问题已解决。我绝对不能相信他们的 SDK...解组到 sqs.Message 类型有效。

标签: go amazon-sqs


【解决方案1】:

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

// 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)

}

【讨论】:

  • 嗨@Cmag,您能否展示将 *sqs.Message 解析为 Go lang 结构的代码。我一直在尝试解析它。
猜你喜欢
  • 2019-11-11
  • 2017-06-09
  • 1970-01-01
  • 2020-07-17
  • 2018-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-03
相关资源
最近更新 更多