
Update the GO tutorials with PublishWithContext instead of Publish Publish is deprecated. As context, I used: `context.WithTimeout(context.Background(), 5*time.Second)` update the Golang Version to 1.7 Signed-off-by: Gabriele Santomaggio G.santomaggio@gmail.com
66 lines
1.2 KiB
Go
66 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
amqp "github.com/rabbitmq/amqp091-go"
|
|
)
|
|
|
|
func failOnError(err error, msg string) {
|
|
if err != nil {
|
|
log.Panicf("%s: %s", msg, err)
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
|
|
failOnError(err, "Failed to connect to RabbitMQ")
|
|
defer conn.Close()
|
|
|
|
ch, err := conn.Channel()
|
|
failOnError(err, "Failed to open a channel")
|
|
defer ch.Close()
|
|
|
|
err = ch.ExchangeDeclare(
|
|
"logs", // name
|
|
"fanout", // type
|
|
true, // durable
|
|
false, // auto-deleted
|
|
false, // internal
|
|
false, // no-wait
|
|
nil, // arguments
|
|
)
|
|
failOnError(err, "Failed to declare an exchange")
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
body := bodyFrom(os.Args)
|
|
err = ch.PublishWithContext(ctx,
|
|
"logs", // exchange
|
|
"", // routing key
|
|
false, // mandatory
|
|
false, // immediate
|
|
amqp.Publishing{
|
|
ContentType: "text/plain",
|
|
Body: []byte(body),
|
|
})
|
|
failOnError(err, "Failed to publish a message")
|
|
|
|
log.Printf(" [x] Sent %s", body)
|
|
}
|
|
|
|
func bodyFrom(args []string) string {
|
|
var s string
|
|
if (len(args) < 2) || os.Args[1] == "" {
|
|
s = "hello"
|
|
} else {
|
|
s = strings.Join(args[1:], " ")
|
|
}
|
|
return s
|
|
}
|