svc.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Package svc helps you write Windows Service executables without getting in the way of other target platforms.
  3. To get started, implement the Init, Start, and Stop methods to do
  4. any work needed during these steps.
  5. Init and Start cannot block. Launch long-running code in a new Goroutine.
  6. Stop may block for a short amount of time to attempt clean shutdown.
  7. Call svc.Run() with a reference to your svc.Service implementation to start your program.
  8. When running in console mode Ctrl+C is treated like a Stop Service signal.
  9. For a full guide visit https://github.com/judwhite/go-svc
  10. */
  11. package svc
  12. import (
  13. "context"
  14. "errors"
  15. "os"
  16. "os/signal"
  17. )
  18. // Create variable signal.Notify function so we can mock it in tests
  19. var signalNotify = signal.Notify
  20. var ErrStop = errors.New("stopping service")
  21. // Service interface contains Start and Stop methods which are called
  22. // when the service is started and stopped. The Init method is called
  23. // before the service is started, and after it's determined if the program
  24. // is running as a Windows Service.
  25. //
  26. // The Start and Init methods must be non-blocking.
  27. //
  28. // Implement this interface and pass it to the Run function to start your program.
  29. type Service interface {
  30. // Init is called before the program/service is started and after it's
  31. // determined if the program is running as a Windows Service. This method must
  32. // be non-blocking.
  33. Init(Environment) error
  34. // Start is called after Init. This method must be non-blocking.
  35. Start() error
  36. // Stop is called when Handle() returns ErrStop or when a
  37. // Windows Service is stopped.
  38. Stop() error
  39. }
  40. // Handler is an optional interface a Service can implement.
  41. // When implemented, Handle() is called when a signal is received.
  42. // Returning ErrStop from this method will result in Service.Stop() being called.
  43. type Handler interface {
  44. Handle(os.Signal) error
  45. }
  46. // Context interface contains an optional Context function which a Service can implement.
  47. // When implemented the context.Done() channel will be used in addition to signal handling
  48. // to exit a process.
  49. type Context interface {
  50. Context() context.Context
  51. }
  52. // Environment contains information about the environment
  53. // your application is running in.
  54. type Environment interface {
  55. // IsWindowsService reports whether the program is running as a Windows Service.
  56. IsWindowsService() bool
  57. }