Go and RabbitMQ
For Go we recommend the github.com/streadway/amqp package.
In this Go example, the code only makes a server verified connection.
package main
import (
"fmt"
"log"
"github.com/streadway/amqp"
)
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
panic(fmt.Sprintf("%s: %s", msg, err))
}
}
func main() {
conn, err := amqp.Dial("amqps://user:[email protected]:10194/Rabbity")
failOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()
Note that the failonError
function shortens the Go error handling.
The main method starts by creating the connection. The RabbitMQ password is passed to the Dial
function. A DialTLS
function also exists, but the use of amqps
in the URL is sufficient to turn on TLS connections.
Using defer
ensures that the connection is closed when exiting.
The rest of the Go code, as with previous examples, opens a channel, creates the exchange and sends a message.
message := "This is not a message, this is a go tribute to a message"
routingKey := "tributes"
exchangeName := "postal"
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
err = ch.ExchangeDeclare(
exchangeName, // name
"direct", // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare an exchange")
err = ch.Publish(
exchangeName, // exchange
routingKey, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(message),
})
failOnError(err, "Failed to publish a message")
}
Still Need Help?
If this article didn't solve things, summon a human and get some help!
Updated over 3 years ago