Skip to content

Instantly share code, notes, and snippets.

@jtickle
Created February 20, 2019 21:59
Show Gist options
  • Save jtickle/034ae2e8be6476de3b75a4bb3d2f7cb8 to your computer and use it in GitHub Desktop.
Save jtickle/034ae2e8be6476de3b75a4bb3d2f7cb8 to your computer and use it in GitHub Desktop.
// This: https://www.rabbitmq.com/tutorials/tutorial-one-go.html
// But without all the copied code between send and receive :)
package main
import (
"os"
"log"
"strings"
"github.com/streadway/amqp"
)
type rabbfunc func(*amqp.Connection, *amqp.Channel, amqp.Queue)
func FailOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}
func WithRabbit(operation rabbfunc) {
conn, err := amqp.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")
operation(conn, ch, q)
}
func buildSend(body string) (rabbfunc) {
return func(conn *amqp.Connection, ch *amqp.Channel, q amqp.Queue) {
err := ch.Publish(
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing {
ContentType: "text/plain",
Body: []byte(body),
})
FailOnError(err, "Failed to publish a message")
}
}
func buildReceive() (rabbfunc) {
return func(conn *amqp.Connection, ch *amqp.Channel, q amqp.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 {
log.Printf("Received a message: %s", d.Body)
}
}()
log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
}
}
func usage() {
panic("Usage: msg [ send <messaage> | receive ]")
}
func main() {
if len(os.Args) < 2 {
usage()
}
switch os.Args[1] {
case "send":
message := strings.Join(os.Args[2:], " ")
WithRabbit(buildSend(message))
case "receive":
WithRabbit(buildReceive())
default:
usage()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment