CloudAMQP with Go Getting started

Client library

The most popular Go client is the Go RabbitMQ library, it is activly maintained by the RabbitMQ team.

Below is a super simple example. In the example we start two different goroutines, one for subscribing and one for publishing. We share the same connection but create a new channel for each goroutine. In the subscribe goroutine, we declare a queue binds that queue to a exchange and then start subscribing. In the publish goroutine we publish a "Hello world" ping message every second.

package main

import (
    "os"
    "fmt"
    "time"

    amqp "github.com/rabbitmq/amqp091-go"
)

func main() {
    url := os.Getenv("CLOUDAMQP_URL")
    if url == "" {
        url = "amqp://localhost"
    }
    connection, _ := amqp.Dial(url)
    defer connection.Close()
    go func(con *amqp.Connection) {
        channel, _ := connection.Channel()
        defer channel.Close()
        durable, exclusive := false, false
        autoDelete, noWait := true, true
        q, _ := channel.QueueDeclare("test", durable, autoDelete, exclusive, noWait, nil)
        channel.QueueBind(q.Name, "#", "amq.topic", false, nil)
        autoAck, exclusive, noLocal, noWait := false, false, false, false
        messages, _ := channel.Consume(q.Name, "", autoAck, exclusive, noLocal, noWait, nil)
        multiAck := false
        for msg := range messages {
            fmt.Println("Body:", string(msg.Body), "Timestamp:", msg.Timestamp)
            msg.Ack(multiAck)
        }
    }(connection)

    go func(con *amqp.Connection) {
        timer := time.NewTicker(1 * time.Second)
        channel, _ := connection.Channel()

        for t := range timer.C {
            msg := amqp.Publishing{
                DeliveryMode: 1,
                Timestamp:    t,
                ContentType:  "text/plain",
                Body:         []byte("Hello world"),
            }
            mandatory, immediate := false, false
            channel.Publish("amq.topic", "ping", mandatory, immediate, msg)
        }
    }(connection)

    select {}
}