Created
July 6, 2022 06:45
-
-
Save farshidboroomand/73be44807a9e973b98b7a786c95ee95b to your computer and use it in GitHub Desktop.
Receive Message from RabbitMQ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
ampq "github.com/rabbitmq/amqp091-go" | |
) | |
func main() { | |
conn, err := ampq.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") | |
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") | |
var forever chan struct{} | |
go func() { | |
for d := range msgs { | |
log.Printf("Received a message: %s", d.Body) | |
} | |
}() | |
log.Printf(" [*] Waiting for messages. To exit press CTRL+C") | |
<-forever | |
} | |
func failOnError(err error, msg string) { | |
if err != nil { | |
log.Panicf("%s: %s", msg, err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
make the file public