0
0
RabbitmqHow-ToBeginner · 4 min read

How to Use RabbitMQ with Go: Simple Guide and Example

To use RabbitMQ with Go, install the github.com/rabbitmq/amqp091-go package, then connect to the RabbitMQ server using amqp.Dial. Use channels to declare queues, publish messages with channel.Publish, and consume messages with channel.Consume.
📐

Syntax

This is the basic syntax to connect to RabbitMQ, declare a queue, publish a message, and consume messages in Go.

  • amqp.Dial(url): Connects to RabbitMQ server.
  • conn.Channel(): Opens a channel for communication.
  • channel.QueueDeclare(): Declares a queue to send/receive messages.
  • channel.Publish(): Sends a message to the queue.
  • channel.Consume(): Receives messages from the queue.
go
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
    // handle error
}
channel, err := conn.Channel()
if err != nil {
    // handle error
}
queue, err := channel.QueueDeclare(
    "queue_name", // name
    false,         // durable
    false,         // delete when unused
    false,         // exclusive
    false,         // no-wait
    nil,           // arguments
)
if err != nil {
    // handle error
}
err = channel.Publish(
    "",           // exchange
    queue.Name,    // routing key
    false,         // mandatory
    false,         // immediate
    amqp.Publishing{
        ContentType: "text/plain",
        Body:        []byte("Hello RabbitMQ!"),
    },
)
if err != nil {
    // handle error
}
msgs, err := channel.Consume(
    queue.Name, // queue
    "",        // consumer
    true,       // auto-ack
    false,      // exclusive
    false,      // no-local
    false,      // no-wait
    nil,        // args
)
if err != nil {
    // handle error
}
for msg := range msgs {
    fmt.Printf("Received: %s\n", msg.Body)
}
💻

Example

This example shows a complete Go program that connects to RabbitMQ, sends a message to a queue, and consumes messages from it.

go
package main

import (
    "fmt"
    "log"
    "github.com/rabbitmq/amqp091-go"
)

func failOnError(err error, msg string) {
    if err != nil {
        log.Fatalf("%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()

    q, err := ch.QueueDeclare(
        "hello", // name
        false,   // durable
        false,   // delete when unused
        false,   // exclusive
        false,   // no-wait
        nil,     // arguments
    )
    failOnError(err, "Failed to declare a queue")

    body := "Hello RabbitMQ from Go!"
    err = ch.Publish(
        "",     // exchange
        q.Name, // routing key
        false,  // mandatory
        false,  // immediate
        amqp.Publishing{
            ContentType: "text/plain",
            Body:        []byte(body),
        })
    failOnError(err, "Failed to publish a message")
    fmt.Printf("Sent: %s\n", body)

    msgs, err := ch.Consume(
        q.Name, // queue
        "",    // consumer
        true,   // auto-ack
        false,  // exclusive
        false,  // no-local
        false,  // no-wait
        nil,    // args
    )
    failOnError(err, "Failed to register a consumer")

    forever := make(chan bool)

    go func() {
        for d := range msgs {
            fmt.Printf("Received: %s\n", d.Body)
        }
    }()

    fmt.Println("Waiting for messages. To exit press CTRL+C")
    <-forever
}
Output
Sent: Hello RabbitMQ from Go! Received: Hello RabbitMQ from Go!
⚠️

Common Pitfalls

Common mistakes when using RabbitMQ with Go include:

  • Not closing connections and channels, which can cause resource leaks.
  • Forgetting to handle errors after each operation.
  • Using auto-ack incorrectly, which can lead to lost messages if the consumer crashes.
  • Declaring queues inconsistently between publisher and consumer.

Always check errors and close resources properly.

go
/* Wrong: Not closing connection and channel, ignoring errors */
conn, _ := amqp.Dial("amqp://guest:guest@localhost:5672/")
ch, _ := conn.Channel()
ch.QueueDeclare("test", false, false, false, false, nil)
ch.Publish("", "test", false, false, amqp.Publishing{ContentType: "text/plain", Body: []byte("msg")})

/* Right: Handle errors and defer close */
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
    log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
    log.Fatal(err)
}
defer ch.Close()
📊

Quick Reference

Here is a quick summary of key RabbitMQ Go client functions:

FunctionPurpose
amqp.Dial(url)Connect to RabbitMQ server
conn.Channel()Open a channel for communication
channel.QueueDeclare()Declare or create a queue
channel.Publish()Send a message to a queue or exchange
channel.Consume()Receive messages from a queue
channel.Close()Close the channel
conn.Close()Close the connection

Key Takeaways

Use the official amqp091-go package to connect and interact with RabbitMQ in Go.
Always check errors and close connections and channels to avoid leaks.
Declare queues consistently on both publisher and consumer sides.
Use channels to publish and consume messages asynchronously.
Avoid auto-acknowledge unless you understand its impact on message reliability.