Add timeout for email service

This commit is contained in:
Paul 2018-01-29 20:55:25 +01:00
parent 4a79379d8e
commit 8b34c53550
2 changed files with 12 additions and 12 deletions

View file

@ -33,7 +33,8 @@ func main() {
SMTPServer: "example.com", SMTPServer: "example.com",
SMTPPort: 25, SMTPPort: 25,
SMTPUsername: "test", SMTPUsername: "test",
SMTPPassword: "test", SMTPPassword: "password",
SMTPTimeout: 5 * time.Second,
From: "Mailtest <test@example.com>", From: "Mailtest <test@example.com>",
}, },
} }
@ -44,12 +45,6 @@ func main() {
// SMTP server // SMTP server
go serviceProvider.Email.Daemon() go serviceProvider.Email.Daemon()
//user := models.User{}
//user.Username = "test"
//user.SetPassword("test")
//fmt.Println(user.HashedPassword)
//fmt.Println(db.Create(&user).Error)
// load and parse template files // load and parse template files
views.LoadTemplates() views.LoadTemplates()

View file

@ -18,6 +18,7 @@ type EmailConfig struct {
SMTPPort int SMTPPort int
SMTPUsername string SMTPUsername string
SMTPPassword string SMTPPassword string
SMTPTimeout time.Duration
} }
type Email struct { type Email struct {
@ -33,7 +34,7 @@ func NewEmail(conf *EmailConfig) *Email {
return &Email{ return &Email{
config: conf, config: conf,
mailChan: make(chan *mail.Message, 0), mailChan: make(chan *mail.Message, 4),
} }
} }
@ -64,6 +65,8 @@ func (email *Email) Daemon() {
return return
} }
log.Print("Running mail sending routine")
d := mail.NewDialer( d := mail.NewDialer(
email.config.SMTPServer, email.config.SMTPServer,
email.config.SMTPPort, email.config.SMTPPort,
@ -78,6 +81,7 @@ func (email *Email) Daemon() {
case m, ok := <-email.mailChan: case m, ok := <-email.mailChan:
if !ok { if !ok {
// channel is closed // channel is closed
log.Print("Channel closed")
return return
} }
if !open { if !open {
@ -87,14 +91,15 @@ func (email *Email) Daemon() {
} }
open = true open = true
} }
log.Printf("Trying to send mail")
if err := mail.Send(s, m); err != nil { if err := mail.Send(s, m); err != nil {
log.Print(err) log.Printf("Mail: %s", err)
} }
// Close the connection if no email was sent in the last 30 seconds. // Close the connection if no email was sent in the last X seconds.
case <-time.After(30 * time.Second): case <-time.After(email.config.SMTPTimeout):
if open { if open {
if err := s.Close(); err != nil { if err := s.Close(); err != nil {
panic(err) log.Printf("Mail: Failed to close connection: %s", err)
} }
open = false open = false
} }