8

我想通过 HTTP 使用 AWS-SDK 在 golang 中通过 AWS IoT 向 MQTT 主题发送消息,但
在尝试使用以下代码时失败。回应是:

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

以下是我使用的代码:

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)

而且我还验证了为我的 AWS 账户验证的有效凭证设置和策略。以下是我在 ~/.aws/credentials 中的 aws 凭证

[default]
aws_access_key_id = YOUR_ACCESS_KEY_ID
aws_secret_access_key = YOUR_SECRET_ACCESS_KEY

和附加到您的身份的政策:

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

}

我也试过用 Node.JS 它工作!以下是Node中的WORKING源码供参考:

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
});

对于 Node JS 的工作,它需要在根文件夹中有一个适当的 AWS.config 文件。像这样:

accessKeyId = YOUR_ACCESS_KEY_ID
secretAccessKey = YOUR_SECRET_ACCESS_KEY
4

1 回答 1

0

如果仍然与任何人相关...在 aws.Config 中使用 Credentials *credentials.Credentials

参见文档: https ://godoc.org/github.com/aws/aws-sdk-go/aws#Config

于 2019-08-21T14:32:06.723 回答