Reputation: 43
I would like to register a Golang executable as a windows service. I'm trying out this package My application is cli application made with Cobra, I'm trying to run a root command when this service starts, But I'm having trouble shutting down the service internally.
Sample code
func (u *UpdateService) Start(s service2.Service) error {
go func() {
ctx, cancel := context.WithCancel(context.Background())
err := Run(ctx, cancel)
if err != nil {
return
}
}()
return nil
}
func (u *UpdateService) Stop(s service2.Service) error {
return nil
}
func Run(ctx context.Context, cancelFunc context.CancelFunc) error {
app := fiber.New()
creationTime := time.Now()
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString(fmt.Sprintf("creation time %s", creationTime.Format(time.RFC3339)))
})
go func() {
time.Sleep(10 * time.Second)
fmt.Println("calling cancelFunc")
cancelFunc()
}()
serverErr := make(chan error, 1)
go func() {
serverErr <- app.Listen(":8080")
}()
select {
case err := <-serverErr:
return err
case <-ctx.Done():
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer shutdownCancel()
return app.ShutdownWithContext(shutdownCtx)
}
}
I can verify that the context is done and the fiber server is shut down successfully but the program itself doesn't exit. My cobra rootCMD
var service *UpdateService
var rootCmd = &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) error {
return service.RunService()
},
}
root cmd calls the interface func Run()
of service package, This was the only way i could get it to run as a windows service after installing. on MacOs this can be omitted but the same problem with shutting down the program remains.
Anybody can steer me into right direction as to what am i missing here?
Update -
err = u.Stop(s) // this cleans up
if err != nil {
return
}
s.Stop() // this shuts down
But the problem of restarting the service remains, I've tried doing os.Exit(-1)
to force the service manager to restart the service but that just crashes the whole computer
Upvotes: 2
Views: 41