interfaces.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package common
  2. // Closable is the interface for objects that can release its resources.
  3. type Closable interface {
  4. // Close release all resources used by this object, including goroutines.
  5. Close() error
  6. }
  7. // Interruptible is an interface for objects that can be stopped before its completion.
  8. type Interruptible interface {
  9. Interrupt()
  10. }
  11. // Close closes the obj if it is a Closable.
  12. func Close(obj interface{}) error {
  13. if c, ok := obj.(Closable); ok {
  14. return c.Close()
  15. }
  16. return nil
  17. }
  18. // Interrupt calls Interrupt() if object implements Interruptible interface, or Close() if the object implements Closable interface.
  19. func Interrupt(obj interface{}) error {
  20. if c, ok := obj.(Interruptible); ok {
  21. c.Interrupt()
  22. return nil
  23. }
  24. return Close(obj)
  25. }
  26. // Runnable is the interface for objects that can start to work and stop on demand.
  27. type Runnable interface {
  28. // Start starts the runnable object. Upon the method returning nil, the object begins to function properly.
  29. Start() error
  30. Closable
  31. }
  32. // HasType is the interface for objects that knows its type.
  33. type HasType interface {
  34. // Type returns the type of the object.
  35. // Usually it returns (*Type)(nil) of the object.
  36. Type() interface{}
  37. }
  38. type ChainedClosable []Closable
  39. func NewChainedClosable(c ...Closable) ChainedClosable {
  40. return ChainedClosable(c)
  41. }
  42. func (cc ChainedClosable) Close() error {
  43. for _, c := range cc {
  44. c.Close()
  45. }
  46. return nil
  47. }