RabbitMQ: Using GoLang to connect to RabbitMQ

This documentation is part of the Getting started guide. You can view the complete guide here: How to use Stackhero for RabbitMQ.

To connect a Go application to RabbitMQ, the official Go RabbitMQ Client Library makes the process straightforward. Here’s how to get started:

  1. Create a new directory and initialise your Go module:
go mod init rabbitmq-example
  1. Next, add the RabbitMQ library to your project:
go get github.com/rabbitmq/amqp091-go
  1. Now, create a file named main.go and add the following code:

    package main
    
    import (
      "fmt"
      amqp "github.com/rabbitmq/amqp091-go"
    )
    
    func main() {
      connection, err := amqp.Dial("amqps://<PASSWORD>@<XXXXXX>.stackhero-network.com:<AMQP_PORT_TLS>")
      if err != nil {
        panic(err)
      }
      defer connection.Close()
    
      fmt.Println("Successfully connected to RabbitMQ instance")
    }
    
  2. Run your code with:

go run main.go

If the connection is successful, you will see the message "Successfully connected to RabbitMQ instance". This means you are securely connected with authentication and TLS encryption.

For more advanced examples, refer to the Go examples in the official RabbitMQ repository: https://github.com/rabbitmq/rabbitmq-tutorials/tree/main/go.