-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
93 lines (77 loc) · 1.97 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"fmt"
"log"
"os"
"github.com/Microkubes/microservice-mail/config"
"github.com/Microkubes/microservice-mail/mail"
"github.com/Microkubes/microservice-tools/rabbitmq"
"github.com/streadway/amqp"
)
func logOnError(err error, msg string) bool {
if err != nil {
fmt.Println(msg, err)
return true
}
return false
}
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf(msg, err)
panic(fmt.Sprintf(msg, err))
}
}
func main() {
cfg := getConfig()
amqpChannel := getAMQPChannel(cfg)
channel := rabbitmq.AMQPChannel{
Channel: amqpChannel,
}
for {
deliveryList, err := channel.Receive("email-queue")
logOnError(err, "Failed to consume the channel")
for delivery := range deliveryList {
go handleDelivery(delivery, cfg)
}
}
}
func handleDelivery(delivery amqp.Delivery, cfg *config.Config) bool {
log.Printf("Received a message: %s", delivery.Body)
message, err := mail.ParseAMQPMessage(&delivery.Body)
if logOnError(err, "Failed to parse AMQP Message") {
delivery.Ack(false)
return false
}
body, err := mail.GenerateMailBody(cfg, &message)
if logOnError(err, "Failed to generate mail body for template "+message.TemplateName) {
delivery.Ack(false)
return false
}
err = mail.SendMail(&message, cfg, &body)
if logOnError(err, "Failed to send mail to "+message.Email) {
delivery.Ack(false)
return false
}
log.Printf("Message to " + message.Email + " sucessfully sended!")
delivery.Ack(false)
return true
}
func getConfig() *config.Config {
cf := os.Getenv("SERVICE_CONFIG_FILE")
if cf == "" {
cf = "/run/secrets/microservice_mail_config.json"
}
cfg, err := config.LoadConfig(cf)
logOnError(err, "Failed to read the config file!")
return cfg
}
func getAMQPChannel(cfg *config.Config) *amqp.Channel {
_, ch, err := rabbitmq.Dial(
cfg.AMQPConfig["username"],
cfg.AMQPConfig["password"],
cfg.AMQPConfig["host"],
cfg.AMQPConfig["port"],
)
failOnError(err, "Failed to connect to AMQP server")
return ch
}