From 56620852e7ac3d7e1ad0c8775cdb348ebdcf260c Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 16 Jun 2021 21:43:11 +0200 Subject: [PATCH] Added debug message and rabbitmq connection --- modules/config/config.go | 7 ++++ modules/database/database.go | 6 ++-- modules/rabbitmq/rabbitmq.go | 65 ++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 modules/rabbitmq/rabbitmq.go diff --git a/modules/config/config.go b/modules/config/config.go index 5a39a89..edbd89a 100644 --- a/modules/config/config.go +++ b/modules/config/config.go @@ -10,6 +10,7 @@ type Config struct { Server server Database database Mail mail + RabbitMq rabbitmq Settings settings } @@ -30,6 +31,12 @@ type mail struct { Key string } +type rabbitmq struct { + Host string + Username string + Password string +} + type settings struct { ExpiredTime int UsernameMinLen int diff --git a/modules/database/database.go b/modules/database/database.go index b297222..6542d01 100644 --- a/modules/database/database.go +++ b/modules/database/database.go @@ -22,7 +22,7 @@ func InitDatabase() { sqlDB, err := sql.Open("mysql", getConnectionString()) if err != nil { - log.Fatalln("DB connection failed:", err) + log.Fatalln("Database connection failed:", err) } sqlDB.SetMaxIdleConns(10) @@ -33,8 +33,10 @@ func InitDatabase() { }), &gorm.Config{}) if err != nil { - log.Fatalln("Failed to open gorm", err) + log.Fatalln("Failed to open gorm ", err) } DB = gormDB + + log.Debugln("Database connected") } diff --git a/modules/rabbitmq/rabbitmq.go b/modules/rabbitmq/rabbitmq.go new file mode 100644 index 0000000..06d3a4c --- /dev/null +++ b/modules/rabbitmq/rabbitmq.go @@ -0,0 +1,65 @@ +package rabbitmq + +import ( + "fmt" + + "git.umbach.dev/app-idea/rest-api/modules/config" + log "github.com/sirupsen/logrus" + "github.com/streadway/amqp" +) + +var Conn *amqp.Connection + +func getConnectionString() string { + cfg := &config.Cfg.RabbitMq + + return fmt.Sprintf("amqp://%s:%s@%s/", cfg.Username, cfg.Password, cfg.Host) +} + +func Init() { + conn, err := amqp.Dial(getConnectionString()) + + if err != nil { + log.Fatalln("Failed to connect to RabbitMQ", err) + } + + Conn = conn + + ch, err := conn.Channel() + + if err != nil { + log.Fatalln("Failed to open a channel", err) + } + + defer ch.Close() + + log.Debug("RabbitMQ connected") + + q, err := ch.QueueDeclare( + "hello", // name + false, // durable + false, // delete when unused + false, // exclusive + false, // no-wait + nil, // arguments + ) + + if err != nil { + log.Fatalln("Failed to declare a queue", err) + } + + body := "Hello World!" + err = ch.Publish( + "", // exchange + q.Name, // routing key + false, // mandatory + false, // immediate + amqp.Publishing{ + ContentType: "text/plain", + Body: []byte(body), + }) + + if err != nil { + log.Fatalln("Failed to publish a message", err) + } +}