在尝试将aws-sdk-go与localstack集成以访问SQS服务时,我需要一些帮助。
我尝试过类似的事情:
result, err := q.Client.SendMessage(&sqs.SendMessageInput{
MessageAttributes: map[string]*sqs.MessageAttributeValue{
"JobName": &sqs.MessageAttributeValue{
DataType: aws.String("String"),
StringValue: aws.String(jobName),
},
},
MessageBody: aws.String(messageBody),
QueueUrl: &q.URL,
})
if err != nil {
return "", err
}
具有如下初始化:
type Queue struct {
Client sqsiface.SQSAPI
URL string
}
var q Queue
func init() {
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
q = Queue{
Client: sqs.New(sess),
URL: viper.GetString("queue.sqs.url"),
}
}
如何配置SDK来访问本地堆栈的SQS?
答案 0 :(得分:0)
假设您已经启动localstack并以默认配置运行,因此SQS
将在端口:4576
上运行,因此可以在http://localhost:4576
进行访问。 / p>
让我们举个例子,在创建会话和队列后,我们在SQS上发送消息:
package main
import (
"encoding/json"
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
const (
// Region represents aws region
Region = "eu-central-1"
// SQSEndpoint represents the sqs endpoint (in this case points to localstack's SQS)
SQSEndpoint = "http://localhost:4576"
// QueueName represents queue's name
QueueName = "some_queue"
// QueueURL represents queue's URL. You can also dynamically retrieve it with sqs.GetQueueUrl
QueueURL = "http://localhost:4576/queue/some_queue"
)
// Message is an example struct representing a message to be sent
type Message struct {
SomeParam string `json:"some_param"`
}
func main() {
// Initialize a new Config
cfg := new(aws.Config)
// Setting up region
cfg.Region = aws.String(Region)
// Setting up SQS Endpoint
cfg.Endpoint = aws.String(SQSEndpoint)
// Initialize new AWS Session
awsSvc, err := session.NewSession(awsSvc)
if err != nil {
log.Fatal(err)
}
// Initialize new SQS Session
sqsSvc := sqs.New(awsSvc)
// Create a new queue input
createQIn := new(sqs.CreateQueueInput)
createQIn = out.SetQueueName(QueueName)
// Create the queue
if _, err := sqsSvc.CreateQueue(createQIn); err != nil {
log.Fatal(err)
}
// Message Input
message := Message {
SomeParam : "some_val"
}
// Build SendMessage Input
sendMsgIn:= new(sqs.SendMessageInput)
// Marshal message to json
b, err:= json.Marshal(input)
if err != nil {
log.Fatal(err)
}
// Set both Body and URL
sendMsgIn = sendMsgIn.SetMessageBody(b).SetQueueUrl(QueueURL)
// Finally send message
if _, err := sqsSvc.SendMessage(sendMsgIn); err != nil {
log.Fatal(err)
}
}
无论如何,我通过一些有用的方法aws-sdk-go-bindings为该SDK实现了一个小型实用程序库。