项目作者: itcomusic

项目描述 :
Run Go Windows Service
高级语言: Go
项目地址: git://github.com/itcomusic/winsvc.git
创建时间: 2018-05-28T10:33:03Z
项目社区:https://github.com/itcomusic/winsvc

开源协议:MIT License

下载


winsvc

Provides creating and running Go Windows Service

Features

  • Restarts service on failure. Service will be restarted:
    1. Threw panic
    2. Exit from run function had happened before context execution canceled (command of the stop was not sent) . winsvc.DisablePanic is option to disable this behavior.
    3. Service had got command but it caught panic
  • context.Context for graceful self shutdown
  • Returns from winsvc.Run if it stops for a long time. winsvc.TimeoutStop is option which it default equals value 20s
  • Package uses os.Chdir for easy using relative path

Install

go get -u github.com/itcomusic/winsvc

Example

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "net/http"
  6. "os"
  7. "time"
  8. "github.com/itcomusic/winsvc"
  9. )
  10. type Application struct {
  11. srv *http.Server
  12. }
  13. func main() {
  14. winsvc.Run(func(ctx context.Context) {
  15. app := New()
  16. if err := app.Run(ctx); err != nil {
  17. log.Printf("[ERROR] rest terminated with error, %s", err)
  18. return
  19. }
  20. log.Printf("[WARN] rest terminated")
  21. })
  22. // service has been just stopped, but process of the go has not stopped yet
  23. // that is why recommendation is to not write any logic
  24. }
  25. func New() *Application {
  26. mux := http.NewServeMux()
  27. server := &http.Server{
  28. Addr: "0.0.0.0:8080",
  29. Handler: mux,
  30. }
  31. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  32. w.WriteHeader(200)
  33. w.Write([]byte("hello winsvc"))
  34. })
  35. mux.HandleFunc("/exit", func(w http.ResponseWriter, r *http.Request) {
  36. // service will be restarted
  37. os.Exit(1)
  38. })
  39. mux.HandleFunc("/shutdown", func(w http.ResponseWriter, r *http.Request) {
  40. // service will be restarted
  41. server.Shutdown(context.TODO())
  42. })
  43. return &Application{srv: server}
  44. }
  45. func (a *Application) Run(ctx context.Context) error {
  46. log.Print("[INFO] started rest")
  47. go func() {
  48. defer log.Print("[WARN] shutdown rest server")
  49. // shutdown on context cancellation
  50. <-ctx.Done()
  51. c, _ := context.WithTimeout(context.Background(), time.Second*5)
  52. a.srv.Shutdown(c)
  53. }()
  54. log.Printf("[INFO] started http server on port :%d", 8080)
  55. return a.srv.ListenAndServe()
  56. }

Using sc.exe

  1. $ sc.exe create "gowinsvc" binPath= "path\gowinsvc.exe" start= auto
  2. $ sc.exe failure "gowinsvc" reset= 0 actions= restart/5000