I'm new to golang, and I would like to refactorate my code so that the rabbitmq initialization is in another function that main. So I use a struct pointer (containing all the rabbitmq infos initilized) and pass it to the send function, but it tells me : Failed to publish a message: Exception (504) Reason: "channel/connection is not open"
struct :
type RbmqConfig struct {
q amqp.Queue
ch *amqp.Channel
conn *amqp.Connection
rbmqErr error
}
the init function :
func initRabbitMq() *RbmqConfig {
config := &RbmqConfig{}
config.conn, config.rbmqErr = amqp.Dial("amqp://guest:guest@localhost:5672/")
failOnError(config.rbmqErr, "Failed to connect to RabbitMQ")
defer config.conn.Close()
config.ch, config.rbmqErr = config.conn.Channel()
failOnError(config.rbmqErr, "Failed to open a channel")
defer config.ch.Close()
config.q, config.rbmqErr = config.ch.QueueDeclare(
"<my_queue_name>",
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(config.rbmqErr, "Failed to declare a queue")
return config
}
main :
config := initRabbitMq()
fmt.Println("queue name : ", config.q.Name)
sendMessage(config, <message_to_send>)
in send message :
func sendMessage(config *RbmqConfig, <message_to_send>) {
config.rbmqErr = config.ch.Publish(
"", // exchange
config.q.Name, // routing key
false, // mandatory
false,
amqp.Publishing{
DeliveryMode: amqp.Persistent,
ContentType: "text/plain",
Body: []byte(<message_to_send>),
})
failOnError(config.rbmqErr, "Failed to publish a message")
If someone has any idea, that would be very helpful. Thank you in advance
Inside your init
, you wrote defer config.conn.Close()
, which will be executed when the function return. That is to say, whenever init
finished, your connection will be closed, which causes unopen connection.
You need to defer the connection closing in main, or somewhere you want it to be closed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With