doushao8399 2015-12-22 06:33
浏览 191

使用Golang-AWS-SDK IoTDataPlane到AWS IoT的HTTP POST

I want to send a message to a MQTT topic via AWS IoT in golang using AWS-SDK via HTTP,
when tried with below code it was unsuccessful. The response was :

ResourceNotFoundException: Not Found
status code: 404, request id: 3d2c0f11-09f6-4e86-94bf-ea877a30ebcd

The following is the code I use:

package main


import (
        "github.com/aws/aws-sdk-go/aws"
        "github.com/aws/aws-sdk-go/aws/session"
        "github.com/aws/aws-sdk-go/service/iotdataplane"
        "fmt"
)


func main(){
svc := iotdataplane.New(session.New(), &aws.Config {Region: aws.String("us-west-2"), Endpoint: aws.String("https://YOUR_PREFIX.iot.us-west-2.amazonaws.com")})

params := &iotdataplane.PublishInput{
        Topic:   aws.String("mytopic"), // Required
        Payload: []byte("PAYLOAD"),
        Qos:     aws.Int64(0),
}
resp, err := svc.Publish(params)

if err != nil {
        // Print the error, cast err to awserr.Error to get the Code and
        // Message from an error.
        fmt.Println(err.Error())
        return
}

// Pretty-print the response data.
fmt.Println(resp)

And I also verified there have valid credential setting and policies verified for my AWS account. The following is my aws credentials in ~/.aws/credentials

[default]
aws_access_key_id = YOUR_ACCESS_KEY_ID
aws_secret_access_key = YOUR_SECRET_ACCESS_KEY

and Policy attached into your identities:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "iot:*"
        ],
        "Resource": "*"
   }
]

}

I also tried with Node.JS it works!! The following is the WORKING source in Node for reference:

var    AWS = require('aws-sdk');

AWS.config.update({region: 'us-west-2'});
var iotdata = new AWS.IotData({endpoint: 'YOUR_PREFIX.iot.us-west-2.amazonaws.com'});


var params = {
  topic: 'mytopic', /* required */
  payload: new Buffer('hello') || 'STRING_VALUE',
  qos: 0
};

iotdata.publish(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

For the Node JS works, it need a proper AWS.config file in the root folder. Like this:

accessKeyId = YOUR_ACCESS_KEY_ID
secretAccessKey = YOUR_SECRET_ACCESS_KEY
  • 写回答

1条回答 默认 最新

  • doudou521125 2019-08-21 14:32
    关注

    If still relevant to anyone... use Credentials *credentials.Credentials in aws.Config

    see docs at: https://godoc.org/github.com/aws/aws-sdk-go/aws#Config

    评论

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接