Skip to content

Instantly share code, notes, and snippets.

@scottillogical
Last active May 1, 2018 19:33
Show Gist options
  • Save scottillogical/e1091aef006d7dbd7044c461a425ddcc to your computer and use it in GitHub Desktop.
Save scottillogical/e1091aef006d7dbd7044c461a425ddcc to your computer and use it in GitHub Desktop.
golang subscribing to rmq queue created events
package main
import (
"fmt"
"log"
"github.com/streadway/amqp"
)
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
panic(fmt.Sprintf("%s: %s", msg, err))
}
}
func main() {
conn, err := amqp.Dial("amqp://admin:admin@127.0.01: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(
"event", // name
false, // durable
false, // delete when usused
true, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue")
err = ch.QueueBind(
q.Name, // queue name
"#", // routing key
"amq.rabbitmq.event", // exchange
false,
nil)
failOnError(err, "Failed to bind 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")
forever := make(chan bool)
go func() {
for d := range msgs {
if d.RoutingKey == "queue.created" {
fmt.Println(d.RoutingKey, d.Headers)
}
}
}()
log.Printf(" [*] Waiting for logs. To exit press CTRL+C")
<-forever
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment