s_headers_parser.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package backends
  2. import (
  3. "github.com/flashmob/go-guerrilla/mail"
  4. )
  5. // ----------------------------------------------------------------------------------
  6. // Processor Name: HeadersParser
  7. // ----------------------------------------------------------------------------------
  8. // Description : Populates the envelope.Header value.
  9. // : It also decodes the subject to UTF-8
  10. //-----------------------------------------------------------------------------------
  11. // Requires : "mimeanalyzer" stream processor to be enabled before it
  12. // ----------------------------------------------------------------------------------
  13. // Config Options: None
  14. // --------------:-------------------------------------------------------------------
  15. // Input : e.MimeParts generated by the mimeanalyzer processor
  16. // ----------------------------------------------------------------------------------
  17. // Output : populates e.Header and e.Subject values of the envelope.
  18. // : Any encoded data in the subject is decoded to UTF-8
  19. // ----------------------------------------------------------------------------------
  20. func init() {
  21. Streamers["headersparser"] = func() *StreamDecorator {
  22. return StreamHeadersParser()
  23. }
  24. }
  25. const stateHeaderScanning = 0
  26. const stateHeaderNotScanning = 1
  27. func StreamHeadersParser() *StreamDecorator {
  28. sd := &StreamDecorator{}
  29. sd.Decorate =
  30. func(sp StreamProcessor, a ...interface{}) StreamProcessor {
  31. var (
  32. state byte
  33. envelope *mail.Envelope
  34. )
  35. sd.Open = func(e *mail.Envelope) error {
  36. state = stateHeaderScanning
  37. envelope = e
  38. return nil
  39. }
  40. sd.Close = func() error {
  41. return nil
  42. }
  43. return StreamProcessWith(func(p []byte) (int, error) {
  44. switch state {
  45. case stateHeaderScanning:
  46. if envelope.MimeParts != nil {
  47. // copy the the headers of the first mime-part to envelope.Header
  48. // then call envelope.ParseHeaders()
  49. if len(*envelope.MimeParts) > 0 {
  50. headers := (*envelope.MimeParts)[0].Headers
  51. if headers != nil && len(headers) > 0 {
  52. state = stateHeaderNotScanning
  53. envelope.Header = headers
  54. _ = envelope.ParseHeaders()
  55. }
  56. }
  57. }
  58. return sp.Write(p)
  59. }
  60. // state is stateHeaderNotScanning
  61. // just forward everything to the underlying writer
  62. return sp.Write(p)
  63. })
  64. }
  65. return sd
  66. }