udemy-go-microservices/broker-service/cmd/api/event/emitter.go

54 lines
860 B
Go

package event
import (
"log"
amqp "github.com/rabbitmq/amqp091-go"
)
type Emitter struct {
conn *amqp.Connection
}
func NewEmitter(conn *amqp.Connection) (Emitter, error) {
emitter := Emitter{
conn: conn,
}
err := emitter.setup()
if err != nil {
return Emitter{}, err
}
return emitter, err
}
func (emitter *Emitter) setup() error {
channel, err := emitter.conn.Channel()
if err != nil {
return err
}
defer channel.Close()
return declaireExchange(channel)
}
func (emitter *Emitter) Push(event string, severity string) error {
ch, err := emitter.conn.Channel()
if err != nil {
return err
}
defer ch.Close()
log.Println("Pushing to channel")
err = ch.Publish("logs_topic", severity, false, false, amqp.Publishing{
ContentType: "text/plain",
Body: []byte(event),
})
if err != nil {
return err
}
return nil
}