Skip to content

Instantly share code, notes, and snippets.

@ragokan
Last active July 8, 2022 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ragokan/1ab1beb8d3a3f8ed0867718fef2f17dd to your computer and use it in GitHub Desktop.
Save ragokan/1ab1beb8d3a3f8ed0867718fef2f17dd to your computer and use it in GitHub Desktop.
RabbitMQ Nest Client Go
package main
import (
"encoding/json"
"github.com/streadway/amqp"
. "gofast/helpers"
. "gofast/types"
"log"
)
func FailOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}
func main() {
conn, err := amqp.Dial("amqp://guest:guest@127.0.0.1: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_queue",
false,
true,
false,
false,
nil,
)
FailOnError(err, "Failed to declare a queue")
msgs, err := ch.Consume(
q.Name,
"hello_queue",
true,
false,
false,
false,
nil,
)
FailOnError(err, "Failed to register a consumer")
forever := make(chan bool)
go func() {
for m := range msgs {
var incomingMessage IncomingMessage
_ = json.Unmarshal(m.Body, &incomingMessage)
// Hard work here
response := OutgoingMessage{
Id: incomingMessage.Id,
Response: "Hello woruld!",
IsDisposed: true,
}
outgoingMessage, _ := json.Marshal(response)
err := ch.Publish(
m.Exchange, m.ReplyTo, false, false,
amqp.Publishing{
ContentType: "text/plain",
CorrelationId: m.CorrelationId,
Body: outgoingMessage,
},
)
FailOnError(err, "Error happened while publishing.")
}
}()
log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
}
package types
type IncomingMessage struct {
Id string `json:"id"`
Data string `json:"data"`
Pattern string `json:"pattern"`
}
type OutgoingMessage struct {
Id string `json:"id"`
Response string `json:"response"`
IsDisposed bool `json:"isDisposed"`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment