Home > Blockchain >  Why will RabbitMQ's PublishWithContext not work with Go?
Why will RabbitMQ's PublishWithContext not work with Go?

Time:10-31

I am learning RabbitMQ through building a small application in GoLang - following this example here: https://www.rabbitmq.com/tutorials/tutorial-one-go.html. My project has the following structure:

project
└───cmd
│   └───api
│   │   main.go
│   └───internal
│   │   rabbitmq.go

And in cmd/internal/rabbitmq.go I have the following code - (errs are delt with):

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

func NewRabbitMQ() (*RabbitMQ, error) {
    // Initialise connection to RabbitMQ
    conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")

    // Initialise Channel
    ch, err := conn.Channel() 

    // Initialise Queue
    q, err := ch.QueueDeclare(
        "hello", // name
        false,   // durable
        false,   // delete when unused
        false,   // exclusive
        false,   // no-wait
        nil,     // arguments
    )

    // Set Context
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    body := "Hello World!"
    err = ch.PublishWithContext( // errors here
       ctx,    // context
       "",     // exchange
       q.Name, // routing key
       false,  // mandatory
       false,  // immediate
       amqp.Publishing{
          ContentType: "text/plain",
          Body:        []byte(body),
       })

    return &RabbitMQ{}, nil
}

As far as I can tell, from the documentation, this is how it should be implemented, so I'm not sure why it is erroring.

I've tried googling to find help with this issue but to no avail. I am using Go 1.19, maybe it is an issue with that?

CodePudding user response:

Thanks to @oakad, this was a simple fix! The issue was the version of RabbitMQ I was using was an older one so I just need to change my go.mod from:

require github.com/rabbitmq/amqp091-go v1.1.0

To:

require github.com/rabbitmq/amqp091-go v1.4.0
  • Related