Running a Go application as a windows service



This week I was looking to run a golang application as a windows service. Came across this neat library by github user kardianos on his github repo. It basically allows you to run Go programs as a service not just on Windows but also on Linux and that other OS (OSX) I dont like to talk about ;)

Following is the source of a simple console application that can run as a windows service with commands for install and uninstall

main.go

 
package main

import (
	"flag"
	"log"

	"github.com/kardianos/service"
)

type program struct{}

func (p *program) Start(s service.Service) error {
	// Should be non-blocking, so run async using goroutine
	go p.run()
	return nil
}

//run will be called by Start() so business logic goes here
func (p *program) run() {
	//your logic here
}
func (p *program) Stop(s service.Service) error {
	// Should be non-blocking
	return nil
}

func main() {

	var mode string
	flag.StringVar(&mode, "mode", "", "install/uninstall/run")
	flag.Parse()

	svcConfig := &service.Config{
		Name:        "GoServiceExampleSimple",
		DisplayName: "Go Service Example",
		Description: "This is an example Go service.",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	if err != nil {
		log.Fatal(err)
	}

	if mode == "install" {
		err = s.Install()
		if err != nil {
			log.Fatal(err)
		}
	}

	if mode == "uninstall" {
		err = s.Uninstall()
		if err != nil {
			log.Fatal(err)
		}
	}

	if mode == "" || mode == "run" {
		err = s.Run()
		if err != nil {
			log.Fatal(err)
		}
	}
}
 

1. Install the service

After running go build main.go, run

 $ ./main.exe  --mode=install 

2. Uninstall the service

 $ ./main.exe  --mode=uninstall 

3. Start the service from services.msc

The name of the service will be the value set in the Name argument in the service.Config{} above. GoServiceExampleSimple in this case.

Copyright (c) 2021 Julien Dcruz