RabbitMQ: Using GoLang to connect to RabbitMQ

This documentation is part of the Getting started guide. View the full guide here: How to use Stackhero for RabbitMQ.

If you would like to connect to RabbitMQ from a Go application, the official Go RabbitMQ Client Library makes it straightforward. Here is how you can get started:

  1. Create a new directory and initialize your Go module:
go mod init rabbitmq-example
  1. Next, you can add the RabbitMQ library to your project:
go get github.com/rabbitmq/amqp091-go
  1. Now, create a file named main.go and add this 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. You can run your code with:

go run main.go

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

For more detailed examples, you might want to check out the Go examples in the official RabbitMQ repository: https://github.com/rabbitmq/rabbitmq-tutorials/tree/main/go.