diff --git a/go.mod b/go.mod index 854f86a..1a0c4e6 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,9 @@ module git.nakama.town/fmartingr/smtp2shoutrrr go 1.23.3 require ( + git.nakama.town/fmartingr/gotoolkit v0.0.0-00010101000000-000000000000 github.com/emersion/go-sasl v0.0.0-20200509203442-7bfe0ed36a21 github.com/emersion/go-smtp v0.21.3 ) + +replace git.nakama.town/fmartingr/gotoolkit => ../gotoolkit diff --git a/main.go b/main.go index bc415f1..7fe3d3e 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "context" "errors" "io" "log" @@ -8,10 +9,38 @@ import ( "net/http" "time" + "git.nakama.town/fmartingr/gotoolkit/model" + "git.nakama.town/fmartingr/gotoolkit/service" "github.com/emersion/go-sasl" "github.com/emersion/go-smtp" ) +var _ model.Server = (*smtpServer)(nil) + +type smtpServer struct { + backend *smtp.Server +} + +func (s *smtpServer) IsEnabled() bool { + return true +} + +func (s *smtpServer) Start(_ context.Context) error { + slog.Info("Started SMTP server", slog.String("addr", s.backend.Addr)) + return s.backend.ListenAndServe() +} + +func (s *smtpServer) Stop(ctx context.Context) error { + slog.Info("Stopping SMTP server") + return s.backend.Shutdown(ctx) +} + +func NewSMTPServer(backend *smtp.Server) model.Server { + return &smtpServer{ + backend: backend, + } +} + // The Backend implements SMTP server methods. type Backend struct{} @@ -79,18 +108,33 @@ func (s *Session) Logout() error { func main() { be := &Backend{} - s := smtp.NewServer(be) + smtpBackend := smtp.NewServer(be) - s.Addr = "localhost:11025" - s.Domain = "localhost" - s.WriteTimeout = 10 * time.Second - s.ReadTimeout = 10 * time.Second - s.MaxMessageBytes = 1024 * 1024 - s.MaxRecipients = 50 - s.AllowInsecureAuth = true + smtpBackend.Addr = "localhost:11025" + smtpBackend.Domain = "localhost" + smtpBackend.WriteTimeout = 10 * time.Second + smtpBackend.ReadTimeout = 10 * time.Second + smtpBackend.MaxMessageBytes = 1024 * 1024 + smtpBackend.MaxRecipients = 50 + smtpBackend.AllowInsecureAuth = true - log.Println("Starting server at", s.Addr) - if err := s.ListenAndServe(); err != nil { - log.Fatal(err) + ctx := context.Background() + smtpServer := NewSMTPServer(smtpBackend) + + svc, err := service.NewService([]model.Server{ + smtpServer, + }) + if err != nil { + slog.Error("Error creating service:", slog.String("err", err.Error())) + return + } + + if err := svc.Start(ctx); err != nil { + slog.Error("Error starting service:", slog.String("err", err.Error())) + return + } + + if err := svc.WaitStop(ctx); err != nil { + slog.Error("Error waiting for service interruption:", slog.String("err", err.Error())) } }