decorate_stream.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package backends
  2. import (
  3. "encoding/json"
  4. "github.com/flashmob/go-guerrilla/mail"
  5. )
  6. type streamOpenWith func(e *mail.Envelope) error
  7. type streamCloseWith func() error
  8. type streamConfigureWith func(cfg ConfigGroup) error
  9. type streamShutdownWith func() error
  10. // We define what a decorator to our processor will look like
  11. // StreamProcessor argument is the underlying processor that we're decorating
  12. // the additional ...interface argument is not needed, but can be useful for dependency injection
  13. type StreamDecorator struct {
  14. // Decorate is called first. The StreamProcessor will be the next processor called
  15. // after this one finished.
  16. Decorate func(StreamProcessor, ...interface{}) StreamProcessor
  17. e *mail.Envelope
  18. // Open is called at the start of each email
  19. Open streamOpenWith
  20. // Close is called when the email finished writing
  21. Close streamCloseWith
  22. // Configure is always called after Decorate, only once for the entire lifetime
  23. // it can open database connections, test file permissions, etc
  24. Configure streamConfigureWith
  25. // Shutdown is called to release any resources before StreamDecorator is destroyed
  26. // typically to close any database connections, cleanup any files, etc
  27. Shutdown streamShutdownWith
  28. // GetEmail returns a reader for reading the data of ab email,
  29. // it may return nil if no email is available
  30. GetEmail func(emailID uint64) (SeekPartReader, error)
  31. }
  32. func (s StreamDecorator) ExtractConfig(cfg ConfigGroup, i interface{}) error {
  33. data, err := json.Marshal(cfg)
  34. if err != nil {
  35. return err
  36. }
  37. err = json.Unmarshal(data, i)
  38. if err != nil {
  39. return err
  40. }
  41. return nil
  42. }
  43. // DecorateStream will decorate a StreamProcessor with a slice of passed decorators
  44. func DecorateStream(c StreamProcessor, ds []*StreamDecorator) (StreamProcessor, []*StreamDecorator) {
  45. for i := range ds {
  46. c = ds[i].Decorate(c)
  47. }
  48. return c, ds
  49. }