Last active
July 8, 2022 19:10
-
-
Save ragokan/1ab1beb8d3a3f8ed0867718fef2f17dd to your computer and use it in GitHub Desktop.
RabbitMQ Nest Client Go
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 ( | |
"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:[email protected]: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 | |
} |
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 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