使用AWS Go SDK将消息发布到SNS

问题描述 投票:0回答:2

我在使用AWS Go SDK向SNS发送消息时遇到问题。发布功能的文档有点模糊。

我的代码是:

package main

import (
    "encoding/json"
    "github.com/aws/aws-sdk-go-v2/aws/external"
    "github.com/aws/aws-sdk-go-v2/service/sns"
    "github.com/aws/aws-sdk-go/aws"
    "log"
)

type Person struct {
    Name string `json:"name"`
} 

func main() {
    cfg, _ := external.LoadDefaultAWSConfig()
    snsClient := sns.New(cfg)

    person := Person{
        Name:"ok",
    }
    jsonStr, _ := json.Marshal(person)

    req := snsClient.PublishRequest(&sns.PublishInput{
        TopicArn: aws.String("arn:aws:sns:us-east-1:*****:ok"),
        Message: aws.String(string(jsonStr)),
        MessageStructure: aws.String("json"),
        MessageAttributes: map[string]sns.MessageAttributeValue{
            "default": {
                DataType: aws.String("String"),
                StringValue: aws.String(string(jsonStr)),
            },
        },
    })

    res, err := req.Send()
    if err != nil {
        log.Fatal(err)
    }

    log.Print(res)
}

当我启动此代码时,我收到以下消息:

2019/01/24 20:14:24 InvalidParameter: Invalid parameter: Message Structure - No default entry in JSON message body
        status code: 400, request id: 55940de1-9645-5485-96c5-592586957ce8
exit status 1

也许有人可以帮助我吗?

谢谢

amazon-web-services go amazon-sns
2个回答
1
投票

我找到了解决问题的方法。

package main

import (
    "encoding/json"
    "github.com/aws/aws-sdk-go-v2/aws/external"
    "github.com/aws/aws-sdk-go-v2/service/sns"
    "github.com/aws/aws-sdk-go-v2/aws"
    "log"
)

type Message struct {
    Default string `json:"default"`
}

type Person struct {
    Name string `json:"name"`
} 

func main() {
    cfg, _ := external.LoadDefaultAWSConfig()
    snsClient := sns.New(cfg)

    person := Person{
        Name: "Felix Kjellberg",
    }
    personStr, _ := json.Marshal(person)

    message := Message{
        Default: string(personStr),
    }
    messageBytes, _ := json.Marshal(message)
    messageStr := string(messageBytes)

    req := snsClient.PublishRequest(&sns.PublishInput{
        TopicArn: aws.String("arn:aws:sns:us-east-1:*****:ok"),
        Message: aws.String(messageStr),
        MessageStructure: aws.String("json"),
    })

    res, err := req.Send()
    if err != nil {log.Fatal(err)
    }

    log.Print(res)
}

需要一些编码开始


0
投票

对于无法使用消息有效负载的订阅者,您必须为json有效负载添加“default”字段。看看这个(向下):https://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-custommessage.html

© www.soinside.com 2019 - 2024. All rights reserved.