s_debug.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package backends
  2. import (
  3. "fmt"
  4. "github.com/flashmob/go-guerrilla/mail"
  5. "time"
  6. )
  7. // ----------------------------------------------------------------------------------
  8. // Processor Name: debugger
  9. // ----------------------------------------------------------------------------------
  10. // Description : Log received emails
  11. // ----------------------------------------------------------------------------------
  12. // Config Options: log_reads bool - log if true
  13. // : sleep_seconds - how many seconds to pause for, useful to force a
  14. // : timeout. If sleep_seconds is 1 then a panic will be induced
  15. // --------------:-------------------------------------------------------------------
  16. // Input : email envelope
  17. // ----------------------------------------------------------------------------------
  18. // Output : none (only output to the log if enabled)
  19. // ----------------------------------------------------------------------------------
  20. func init() {
  21. Streamers["debug"] = func() *StreamDecorator {
  22. return StreamDebug()
  23. }
  24. }
  25. type streamDebuggerConfig struct {
  26. LogReads bool `json:"log_reads"`
  27. SleepSec int `json:"sleep_seconds,omitempty"`
  28. }
  29. func StreamDebug() *StreamDecorator {
  30. sd := &StreamDecorator{}
  31. var config streamDebuggerConfig
  32. sd.Configure = func(cfg *ConfigGroup) error {
  33. return sd.ExtractConfig(cfg, &config)
  34. }
  35. sd.Decorate =
  36. func(sp StreamProcessor, a ...interface{}) StreamProcessor {
  37. sd.Open = func(e *mail.Envelope) error {
  38. return nil
  39. }
  40. return StreamProcessWith(func(p []byte) (int, error) {
  41. str := string(p)
  42. if config.LogReads {
  43. fmt.Print(str)
  44. Log().WithField("p", string(p)).Info("Debug stream")
  45. }
  46. if config.SleepSec > 0 {
  47. Log().Infof("sleeping for %d", config.SleepSec)
  48. time.Sleep(time.Second * time.Duration(config.SleepSec))
  49. Log().Infof("woke up")
  50. if config.SleepSec == 1 {
  51. panic("panic on purpose")
  52. }
  53. }
  54. return sp.Write(p)
  55. })
  56. }
  57. return sd
  58. }