Friday, July 26, 2013

Windows Service with Go - the easy way

This is a quick and dirty way to create a Windows Service using Go.

First, you create a normal Go program with a main() function. This calls another method where the actual work gets done. This function runs in an infinite loop (if you're writing a Go web server, you don't need this loop as the http listener will take care of this).

package main

func main() {
 //Call this function where the action happpens
 doStuff()
}

func doStuff() {
 for {
  //the actual stuff happens here.
 }
}

Once you build this to an exe file, register it as a service using the wonderful NSSM (the Non-Sucking Service Manager). In our case, that would be -

nssm install MyService d:\MyService.exe

(where d:\MyService.exe is the full path to the exe file).

This will register the exe as a Windows Service named MyService. You can change the settings of this service by typing Services.msc and choosing MyService from the services list.


You can delete this service using either NSSM or the native service control sc.exe

sc delete MyService

This method is pure Go and does not use any native Windows APIs directly. The advantage of this is that the same Go program can be run on another OS, if required.

If you want to write something Windows-specific and take advantage of native APIs, like writing to the Windows Event Log, you can use this package from +Alex Brainman.

No comments:

Post a Comment