1
0

email_writer.go 751 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package logger
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. )
  7. type EmailWriter struct {
  8. recipient string
  9. subject string
  10. smtpClient SMTPClient
  11. }
  12. func NewEmailWriter(smtpClient SMTPClient, recipient string, subject string) (*EmailWriter, error) {
  13. if len(recipient) == 0 {
  14. return nil, errors.New("empty recipient")
  15. }
  16. if smtpClient == nil {
  17. return nil, errors.New("empty smtp client")
  18. }
  19. return &EmailWriter{
  20. recipient: recipient,
  21. subject: subject,
  22. smtpClient: smtpClient,
  23. }, nil
  24. }
  25. func (w EmailWriter) Write(p []byte) (int, error) {
  26. var out bytes.Buffer
  27. if err := json.Indent(&out, p, "", " "); err != nil {
  28. return 0, err
  29. }
  30. err := w.smtpClient.Send(w.recipient, w.subject, out.String(), false)
  31. return 0, err
  32. }