closer.go 976 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Package closer provides signaling channel for shutdown
  2. package closer
  3. import (
  4. "context"
  5. )
  6. // Closer allows for each signaling a channel for shutdown
  7. type Closer struct {
  8. ctx context.Context
  9. closeFunc func()
  10. }
  11. // NewCloser creates a new instance of Closer
  12. func NewCloser() *Closer {
  13. ctx, closeFunc := context.WithCancel(context.Background())
  14. return &Closer{
  15. ctx: ctx,
  16. closeFunc: closeFunc,
  17. }
  18. }
  19. // NewCloserWithParent creates a new instance of Closer with a parent context
  20. func NewCloserWithParent(ctx context.Context) *Closer {
  21. ctx, closeFunc := context.WithCancel(ctx)
  22. return &Closer{
  23. ctx: ctx,
  24. closeFunc: closeFunc,
  25. }
  26. }
  27. // Done returns a channel signaling when it is done
  28. func (c *Closer) Done() <-chan struct{} {
  29. return c.ctx.Done()
  30. }
  31. // Err returns an error of the context
  32. func (c *Closer) Err() error {
  33. return c.ctx.Err()
  34. }
  35. // Close sends a signal to trigger the ctx done channel
  36. func (c *Closer) Close() {
  37. c.closeFunc()
  38. }