embed http server

This commit is contained in:
rmanach 2023-09-09 16:41:43 +02:00
parent 4d0076e625
commit 5a43b094bb

View File

@ -1,7 +1,9 @@
package services
import (
"encoding/json"
"fmt"
"io"
cfg "mailsrv/config"
"mailsrv/mail"
"mailsrv/runtime"
@ -12,6 +14,7 @@ import (
"syscall"
"time"
"net/http"
"net/smtp"
"github.com/rs/zerolog/log"
@ -43,7 +46,6 @@ func (s Sender) SendMail(email mail.Email) error {
log.Debug().Msg("SMTP authentication succeed")
if err := smtp.SendMail(s.smtpConfig.GetFullUrl(), auth, email.Sender, email.GetReceivers(), email.Generate()); err != nil {
log.Err(err).Msg("error while sending email")
return err
}
@ -51,6 +53,35 @@ func (s Sender) SendMail(email mail.Email) error {
return nil
}
func (s Sender) mailHandler(w http.ResponseWriter, r *http.Request) {
content, err := io.ReadAll(r.Body)
if err != nil {
log.Err(err).Msg("unable to read request body")
w.WriteHeader(http.StatusInternalServerError)
return
}
var mail mail.Email
if err := json.Unmarshal(content, &mail); err != nil {
log.Err(err).Msg("unable to deserialized request body into mail")
w.WriteHeader(http.StatusInternalServerError)
return
}
s.queue.Add(mail)
w.WriteHeader(http.StatusOK)
}
func (s Sender) runHTTPserver() {
mux := http.NewServeMux()
mux.HandleFunc("/mail", s.mailHandler)
if err := http.ListenAndServe(":1212", mux); err != nil {
log.Err(err).Msg("http server stops listening")
}
}
// watchOutbox reads the `outbox` directory every `TickInterval` and put JSON format e-mail in the queue.
func (s Sender) watchOutbox() {
log.Info().Str("outbox", s.outboxPath).Msg("start watching outbox directory")
@ -149,6 +180,8 @@ func (s Sender) Run() {
s.watchOutbox()
chQueue := s.run()
go s.runHTTPserver()
select {
case <-chSignal:
log.Warn().Msg("stop signal received, stopping e-mail queue...")