interfaces.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package common
  2. import "github.com/xtls/xray-core/common/errors"
  3. // Closable is the interface for objects that can release its resources.
  4. //
  5. // xray:api:beta
  6. type Closable interface {
  7. // Close release all resources used by this object, including goroutines.
  8. Close() error
  9. }
  10. // Interruptible is an interface for objects that can be stopped before its completion.
  11. //
  12. // xray:api:beta
  13. type Interruptible interface {
  14. Interrupt()
  15. }
  16. // Close closes the obj if it is a Closable.
  17. //
  18. // xray:api:beta
  19. func Close(obj interface{}) error {
  20. if c, ok := obj.(Closable); ok {
  21. return c.Close()
  22. }
  23. return nil
  24. }
  25. // Interrupt calls Interrupt() if object implements Interruptible interface, or Close() if the object implements Closable interface.
  26. //
  27. // xray:api:beta
  28. func Interrupt(obj interface{}) error {
  29. if c, ok := obj.(Interruptible); ok {
  30. c.Interrupt()
  31. return nil
  32. }
  33. return Close(obj)
  34. }
  35. // Runnable is the interface for objects that can start to work and stop on demand.
  36. type Runnable interface {
  37. // Start starts the runnable object. Upon the method returning nil, the object begins to function properly.
  38. Start() error
  39. Closable
  40. }
  41. // HasType is the interface for objects that knows its type.
  42. type HasType interface {
  43. // Type returns the type of the object.
  44. // Usually it returns (*Type)(nil) of the object.
  45. Type() interface{}
  46. }
  47. // ChainedClosable is a Closable that consists of multiple Closable objects.
  48. type ChainedClosable []Closable
  49. // Close implements Closable.
  50. func (cc ChainedClosable) Close() error {
  51. var errs []error
  52. for _, c := range cc {
  53. if err := c.Close(); err != nil {
  54. errs = append(errs, err)
  55. }
  56. }
  57. return errors.Combine(errs...)
  58. }