# Running Go Programs as a Background Process

- Published: June 24, 2013
- Author: William Kennedy
- URL: https://www.ardanlabs.com/blog/2013/06/running-go-programs-as-background.html

I have been writing Windows services in C/C++ and then in C# since 1999. Now that I am writing server based software in Go for the Linux OS I am completely lost. What is even more&nbsp;frustrating,&nbsp;is that for the first time the OS I am developing on (Mac OSX) is not the operating system I will be deploying my code on. That will be for another blog post.

<br />
<br />
I want to run my code as a background process (daemon) on my Mac. My only problem is, I have no idea how that works on the Mac OS.<br />
<br />
I was lucky to find an open source project called <a href="https://bitbucket.org/kardianos/service/src" target="">service</a> on Bitbucket by Daniel Theophanes. This code taught me how to create, install, start and stop daemons on the Mac OS. The code also supports daemons for the Linux OS and Windows.<br />
<br />
<b>Background Processes on the Mac OS</b><br />
<b><br /></b>
The Mac OS has two types of background processes, Daemons and Agents. Here is a definition for each:<br />
<br />
A <b>daemon</b> is a program that runs in the background as part of the overall system (that is, it is not tied to a particular user). A daemon cannot display any GUI; more specifically, it is not allowed to connect to the window server. A web server is the perfect example of a daemon.<br />
<br />
<div>
An <b>agent</b> is a process that runs in the background on behalf of a particular user. Agents are useful because they can do things that daemons can't, like reliably access the user's home directory or connect to the window server.<br />
<br /></div>
<div>
For More Information:</div>
<div>
[http://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/Introduction.html](/broken-link)
<br />
<span style="background-color: white; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Helvetica, Arial, Verdana, sans-serif; font-size: 13px;"><br /></span>
Let's start with how to configure a daemon in the Mac OS.<br />
<br />
<div class="separator" style="margin:0 auto; display:block; width:640px;">
![Screen Shot](../../../images/goinggo/Screen-Shot-2013-07-28-at-9.51.35-AM.png)
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div style="clear: both;">
</div>
If you open up finder you will see the following folders. The LaunchDaemons folder under Library is where we we need to add a launchd .plist file. There is also a Library/LaunchDaemons folder under /System for the OS daemons.<br />
<br />
The launchd program is the service management framework for starting, stopping and managing daemons, applications, processes, and scripts in the Mac OS. Once the kernel starts&nbsp;launchd, the program scans several directories including /etc for scripts and the LaunchAgents and LaunchDaemons folders in both /Library and /System/Library. Programs found in the LaunchDaemons directories are run as the root user.<br />
<br />
Here is the version of the launchd .plist file with all the basic configuration we need:<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;">&lt;?xml version='1.0' encoding='UTF-8'?&gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;">&lt;!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"[http://www.apple.com/DTDs/PropertyList-1.0.dtd](/broken-link)\" &gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;">&lt;plist version='1.0'&gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;">&lt;dict&gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;"><span class="Apple-tab-span" style="white-space: pre;"> </span>&lt;key&gt;Label&lt;/key&gt;&lt;string&gt;My Service&lt;/string&gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;"><span class="Apple-tab-span" style="white-space: pre;"> </span>&lt;key&gt;ProgramArguments&lt;/key&gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;"><span class="Apple-tab-span" style="white-space: pre;"> </span>&lt;array&gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;"><span class="Apple-tab-span" style="white-space: pre;">  </span>&lt;string&gt;/Users/bill/MyService/MyService&lt;/string&gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;"><span class="Apple-tab-span" style="white-space: pre;"> </span>&lt;/array&gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;"><span class="Apple-tab-span" style="white-space: pre;"> </span>&lt;key&gt;WorkingDirectory&lt;/key&gt;&lt;string&gt;</span><span style="font-family: 'Courier New', Courier, monospace; font-size: x-small;">/Users/bill/MyService</span><span style="font-family: Courier New, Courier, monospace; font-size: x-small;">&lt;/string&gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;"><span class="Apple-tab-span" style="white-space: pre;"> </span>&lt;key&gt;StandardOutPath&lt;/key&gt;&lt;string&gt;</span><span style="font-family: 'Courier New', Courier, monospace; font-size: x-small;">/Users/bill/MyService</span><span style="font-family: Courier New, Courier, monospace; font-size: x-small;">/My.log&lt;/string&gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;"><span class="Apple-tab-span" style="white-space: pre;"> </span>&lt;key&gt;KeepAlive&lt;/key&gt;&lt;true/&gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;"><span class="Apple-tab-span" style="white-space: pre;"> </span>&lt;key&gt;Disabled&lt;/key&gt;&lt;false/&gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;">&lt;/dict&gt;</span><br />
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;">&lt;/plist&gt;</span>
</div>
<br />
You can find all the different options for the .plist file here:<br />
[https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man5/launchd.plist.5.html](/broken-link)
<br />
<br />
The ProgramArguments key is an important tag:<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
&lt;key&gt;ProgramArguments&lt;/key&gt;<br />
&lt;array&gt;<br />
&nbsp; &nbsp; &lt;string&gt;/Users/bill/MyService/MyService&lt;/string&gt;<br />
&lt;/array&gt;
</div>
<br />
Here you specify the name of the program to run and any other arguments to be passed into main.<br />
<br />
These other two tags, WorkingDirectory and StandardOutPath are real helpful too:<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
&lt;key&gt;WorkingDirectory&lt;/key&gt;&lt;string&gt;/Users/bill/MyService&lt;/string&gt;<br />
&lt;key&gt;StandardOutPath&lt;/key&gt;&lt;string&gt;/Users/bill/MyService/My.log&lt;/string&gt;
</div>
<br />
Once we have a launchd .plist file we can use a special program called launchctl to start our program as a background process (daemon).<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
launchctl load /Library/LaunchDaemons/MyService.plist
</div>
<br />
The launchctl program provides service control and reporting. The load command is used to start a daemon based on the launchd .plist file. To verify that a program is running use the list command:<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
launchctl list<br />
<br />
PID &nbsp;Status &nbsp;Label<br />
948 &nbsp;- &nbsp; &nbsp; &nbsp; 0x7ff4a9503410.anonymous.launchctl<br />
946 &nbsp;- &nbsp; &nbsp; &nbsp; My Service<br />
910 &nbsp;- &nbsp; &nbsp; &nbsp; 0x7ff4a942ce00.anonymous.bash
</div>
<br />
PID 946 was assigned to the running program, My Service. Now to stop the program from running issue an unload command:<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
launchctl unload /Library/LaunchDaemons/MyService.plist<br />
launchctl list<br />
<br />
PID &nbsp;Status &nbsp;Label<br />
948 &nbsp;- &nbsp; &nbsp; &nbsp; 0x7ff4a9503410.anonymous.launchctl<br />
910 &nbsp;- &nbsp; &nbsp; &nbsp; 0x7ff4a942ce00.anonymous.bash</div>
<br />
Now the program has been terminated. There is some code we need to implement to handle the start and stop requests from the OS when our program is started and terminated.<br />
<br />
<b>OS Specific Go Coding Files</b><br />
<br />
You can create Go source code files that are only compiled for the target platform you're building.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: left; float: left; margin:0 auto; display:block; width:320px;">
![Screen Shot](../../../images/goinggo/Screen-Shot-2013-07-28-at-9.52.55-AM.png)
</div>

<br />
In my LiteIDE project for Going Go you will see five Go source code files. Three of these files have the name of an environment we can build the code for, darwin (Mac), linux and windows.<br />
<br />
Since I am building against the Mac OS, the service_linux.go and service_windows.go files are&nbsp;ignored&nbsp;by the compiler.<br />
<br />
The compiler recognizes this naming convention by default.<br />
<br /></div>
<div style="clear: both;">
</div>
This is very cool because each environment needs to do a few things differently and use different packages. As in the case of service_windows.go, the following imports are required:<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
"code.google.com/p/winsvc/eventlog"<br />
"code.google.com/p/winsvc/mgr"<br />
"code.google.com/p/winsvc/svc"
</div>
<br />
I don't have these packages installed right now because I don't plan to run the code on windows. It doesn't affect building the code because service_windows.go is ignored.<br />
<br />
There is another really cool side effect from this, I can reuse types and function names within these files since only one of these files are ever compiled with the program. This means that any code that uses this package does not have to be modified when changing environments. &nbsp;Really Cool !!<br />
<br />
<b>Service Interfaces</b><br />
<br />
Each service must implement three interfaces that provide command and control for the service.<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
type Service interface {<br />
&nbsp; &nbsp; Installer<br />
&nbsp; &nbsp; Controller<br />
&nbsp; &nbsp; Runner<br />
}<br />
<br />
type Installer interface {<br />
&nbsp; &nbsp; Install(config &#42;Config) error<br />
&nbsp; &nbsp; Remove() error<br />
}<br />
<br />
type Controller interface {<br />
&nbsp; &nbsp; Start() error<br />
&nbsp; &nbsp; Stop() error<br />
}
<br />
<br />
type Runner interface {<br />
&nbsp; &nbsp; Run(config &#42;Config) error<br />
}</div>
<br />
The Installer interface provides the logic for installing and uninstalling the program as a background process on the specific OS. The Controller interface provides logic to start and stop the service from the command line. The final interface Runner is used to perform all application logic and run the program as a service when requested.<br />
<br />
<b>Darwin Implementation</b><br />
<b><br /></b>
Since this post is specific to the Mac OS I will concentrate on the implementation of the service_darwin.go code file.<br />
<br />
The Installer interface requires the implementation of two functions, Install and Remove. As described above we need to create a launchd .plist file for the service. The best way to accomplish this is to use the text/template package.<br />
<br />
The _InstallScript function uses a multi-line string to create the template for the launchd .plist file.<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
func _InstallScript() (script string) {<br />
&nbsp; &nbsp; return `&lt;?xml version='1.0' encoding='UTF-8'?&gt;<br />
&lt;!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"[ http://www.apple.com/DTDs/PropertyList-1.0.dtd ](/broken-link)\" &gt;<br />
&lt;plist version='1.0'&gt;<br />
&lt;dict&gt;<br />
&nbsp; &nbsp; &lt;key&gt;Label&lt;/key&gt;&lt;string&gt;<b>{{.DisplayName}}</b>&lt;/string&gt;<br />
&nbsp; &nbsp; &lt;key&gt;ProgramArguments&lt;/key&gt;<br />
&nbsp; &nbsp; &lt;array&gt;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &lt;string&gt;<b>{{.WorkingDirectory}}</b>/<b>{{.ExecutableName}}</b>&lt;/string&gt;<br />
&nbsp; &nbsp; &lt;/array&gt;<br />
&nbsp; &nbsp; &lt;key&gt;WorkingDirectory&lt;/key&gt;&lt;string&gt;<b>{{.WorkingDirectory}}</b>&lt;/string&gt;<br />
&nbsp; &nbsp; &lt;key&gt;StandardOutPath&lt;/key&gt;&lt;string&gt;<b>{{.LogLocation}}</b>/<b>{{.Name}}</b>.log&lt;/string&gt;<br />
&nbsp; &nbsp; &lt;key&gt;KeepAlive&lt;/key&gt;&lt;true/&gt;<br />
&nbsp; &nbsp; &lt;key&gt;Disabled&lt;/key&gt;&lt;false/&gt;<br />
&lt;/dict&gt;<br />
&lt;/plist&gt;`<br />
}</div>
<br />
What is cool about multi-line strings is that the carriage return, line feeds and spaces are respected. &nbsp;Since this is a template, we need to have variables that will be&nbsp;substituted with data. &nbsp;The {{.variable_name}} convention is used to define those variables.<br />
<br />
Here is the&nbsp;implementation&nbsp;of the Install function:<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
func (service &#42;_DarwinLaunchdService) Install(config &#42;Config) error {<br />
&nbsp; &nbsp; confPath := service._GetServiceFilePath()<br />
<br />
&nbsp; &nbsp; _, err := os.Stat(confPath)<br />
&nbsp; &nbsp; if err == nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; return fmt.Errorf("Init already exists: %s", confPath)<br />
&nbsp; &nbsp; }<br />
<br />
&nbsp; &nbsp; file, err := os.Create(confPath)<br />
&nbsp; &nbsp; if err != nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; return err<br />
&nbsp; &nbsp; }<br />
&nbsp; &nbsp; defer file.Close()<br />
<br />
&nbsp; &nbsp; parameters := struct {<br />
&nbsp; &nbsp; &nbsp; &nbsp; ExecutableName string<br />
&nbsp; &nbsp; &nbsp; &nbsp; WorkingDirectory string<br />
&nbsp; &nbsp; &nbsp; &nbsp; Name string<br />
&nbsp; &nbsp; &nbsp; &nbsp; DisplayName string<br />
&nbsp; &nbsp; &nbsp; &nbsp; LongDescription string<br />
&nbsp; &nbsp; &nbsp; &nbsp; LogLocation string<br />
&nbsp; &nbsp; }{<br />
&nbsp; &nbsp; &nbsp; &nbsp; service._Config.ExecutableName,<br />
&nbsp; &nbsp; &nbsp; &nbsp; service._Config.WorkingDirectory,<br />
&nbsp; &nbsp; &nbsp; &nbsp; service._Config.Name,<br />
&nbsp; &nbsp; &nbsp; &nbsp; service._Config.DisplayName,<br />
&nbsp; &nbsp; &nbsp; &nbsp; service._Config.LongDescription,<br />
&nbsp; &nbsp; &nbsp; &nbsp; service._Config.LogLocation,<br />
&nbsp; &nbsp; }<br />
<br />
&nbsp; &nbsp; template := template.Must(template.New("launchdConfig").Parse(_InstallScript()))<br />
&nbsp; &nbsp; return template.Execute(file, &amp;parameters)<br />
}</div>
<br />
The _GetServiceFilePath() abstracts the location of the configuration file for each environment implementation. For Darwin the function looks like this:<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
func (service &#42;_DarwinLaunchdService) _GetServiceFilePath() string {<br />
&nbsp; &nbsp; return fmt.Sprintf("/Library/LaunchDaemons/%s.plist", service._Config.Name)<br />
}</div>
<br />
Now the code checks if the file already exists and if it doesn't, creates an empty file. Next we build a struct on the fly and populate it with all the parameters that we need for the template Execute function call. Notice the names of the fields match the {{.variable_name}} variables in the template.<br />
<br />
The Execute function will process the template and then write the finished product to disk using the file handle.<br />
<br />
The Controller interface requires two functions, Start and Stop. In the Darwin source code file the implementation is simple:<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
func (service &#42;_DarwinLaunchdService) Start() error {<br />
&nbsp; &nbsp; confPath := service._GetServiceFilePath()<br />
<br />
&nbsp; &nbsp; cmd := exec.Command("launchctl", "load", confPath)<br />
&nbsp; &nbsp; return cmd.Run()<br />
}<br />
<br />
func (service &#42;_DarwinLaunchdService) Stop() error {<br />
&nbsp; &nbsp; confPath := service._GetServiceFilePath()<br />
<br />
&nbsp; &nbsp; cmd := exec.Command("launchctl", "unload", confPath)<br />
&nbsp; &nbsp; return cmd.Run()<br />
}</div>
<br />
Each function executes the launchctl program the same way as we did above. This provides a&nbsp;convenient way&nbsp;to start and stop the daemon.<br />
<br />
The final interface that needs to be implemented is Runner with one function called Run.<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
func (service &#42;_DarwinLaunchdService) Run(config &#42;Config) error {<br />
&nbsp; &nbsp; defer func() {<br />
&nbsp; &nbsp; &nbsp; &nbsp; if r := recover(); r != nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("&#42;&#42;&#42;&#42;&#42;&#42;&gt; SERVICE PANIC:", r)<br />
&nbsp; &nbsp; &nbsp; &nbsp; }<br />
&nbsp; &nbsp; }()<br />
<br />
&nbsp; &nbsp; fmt.Print("&#42;&#42;&#42;&#42;&#42;&#42;&gt; Initing Service\n")<br />
<br />
&nbsp; &nbsp; if config.Init != nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; if err := config.Init(); err != nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return err<br />
&nbsp; &nbsp; &nbsp; &nbsp; }<br />
&nbsp; &nbsp; }<br />
<br />
&nbsp; &nbsp; fmt.Print("&#42;&#42;&#42;&#42;&#42;&#42;&gt; Starting Service\n")<br />
<br />
&nbsp; &nbsp; if config.Start != nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; if err := config.Start(); err != nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return err<br />
&nbsp; &nbsp; &nbsp; &nbsp; }<br />
&nbsp; &nbsp; }<br />
<br />
&nbsp; &nbsp; fmt.Print("&#42;&#42;&#42;&#42;&#42;&#42;&gt; Service Started\n")<br />
<br />
&nbsp; &nbsp; // Create a channel to talk with the OS<br />
&nbsp; &nbsp; var sigChan = make(chan os.Signal, 1)<br />
&nbsp; &nbsp; signal.Notify(sigChan, os.Interrupt)<br />
<br />
&nbsp; &nbsp; // Wait for an event<br />
&nbsp; &nbsp; whatSig := &lt;-sigChan<br />
<br />
&nbsp; &nbsp; fmt.Print("&#42;&#42;&#42;&#42;&#42;&#42;&gt; Service Shutting Down\n")<br />
<br />
&nbsp; &nbsp; if config.Stop != nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; if err := config.Stop(); err != nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return err<br />
&nbsp; &nbsp; &nbsp; &nbsp; }<br />
&nbsp; &nbsp; }<br />
<br />
&nbsp; &nbsp; fmt.Print("&#42;&#42;&#42;&#42;&#42;&#42;&gt; Service Down\n")<br />
&nbsp; &nbsp; return nil<br />
}</div>
<br />
Run is called when the program is going to run as daemon. It first makes a call to the users onInit and onStart functions. The user is expected to perform any initialization, start their routines and then return control back.<br />
<br />
Next the code creates a channel that will be used to communicate with the operating system. The call to signal.Notify binds the channel to receive operating system events. The code then starts an endless loop and waits until the operating system notifies the program with an event. The code is looking for any events that tell it to shutdown. Once an event to shutdown is received, the user onStop function is called and the Run function returns control back to shutdown the program.<br />
<br />
<b>Service Manager</b><br />
<b><br /></b>
Service Manager provides all the boilerplate code so Service can be easily implemented by any program. It implements the Config member function called Run.<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
func (config &#42;Config) Run() {<br />
&nbsp; &nbsp; var err error<br />
&nbsp; &nbsp;&nbsp;config.Service, err = NewService(config)<br />
&nbsp; &nbsp; if err != nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s unable to start: %s", config.DisplayName, err)<br />
&nbsp; &nbsp; &nbsp; &nbsp; return<br />
&nbsp; &nbsp; }<br />
<br />
&nbsp; &nbsp; // Perform a command and then return<br />
&nbsp; &nbsp; if len(os.Args) &gt; 1 {<br />
&nbsp; &nbsp; &nbsp; &nbsp; verb := os.Args[1]<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; switch verb {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case "install":<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if err := service.Install(config); err != nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Failed to install:", err)<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("Service \"%s\" installed.\n", config.DisplayName)<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case "remove":<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if err := service.Remove(); err != nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Failed to remove:", err)<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("Service \"%s\" removed.\n", config.DisplayName)<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case "debug":<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; config.Start(config)<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Starting Up In Debug Mode")<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reader := bufio.NewReader(os.Stdin)<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reader.ReadString('\n')<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Shutting Down")<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; config.Stop(config)<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case "start":<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if err := service.Start(); err != nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fmt.Println("Failed to start:", err)<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fmt.Printf("Service \"%s\" started.\n", config.DisplayName)<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case "stop":<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if err := service.Stop(); err != nil {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fmt.Println("Failed to stop:", err)<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fmt.Printf("Service \"%s\" stopped.\n", config.DisplayName)<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;default:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fmt.Printf("Options for \"%s\": (install | remove | debug | start | stop)\n", os.Args[0])<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return<br />
&nbsp; &nbsp; &nbsp; &nbsp; }<br />
&nbsp; &nbsp; }<br />
<br />
&nbsp; &nbsp; // Run the service<br />
&nbsp; &nbsp; service.Run(config)<br />
}</div>
<br />
The Run function starts by creating the service object based on the configuration that is provided. Then it looks to at the command line arguments. If there is a command, it is processed and the program terminates. If the command is debug, the program is started as if it were running as a service except it does not hook into the operating system. Hitting the &lt;enter&gt; kill will shut down the program.<br />
<br />
If no command line arguments are provided, the code attempts to start as a daemon by calling service.Run.<br />
<br />
<b>Implementing The Service</b><br />
<b><br /></b>
The following code shows an example of using the service:<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
package main<br />
<br />
import (<br />
&nbsp; &nbsp; "fmt"<br />
&nbsp; &nbsp; "path/filepath"<br />
<br />
&nbsp; &nbsp; "github.com/goinggo/service/v1"<br />
)<br />
<br />
func main() {<br />
&nbsp; &nbsp; // Capture the working directory<br />
&nbsp; &nbsp; workingDirectory, _ := filepath.Abs("")<br />
<br />
&nbsp; &nbsp; // Create a config object to start the service<br />
&nbsp; &nbsp; config := service.Config{<br />
&nbsp; &nbsp; &nbsp; &nbsp; ExecutableName: "MyService",<br />
&nbsp; &nbsp; &nbsp; &nbsp; WorkingDirectory: workingDirectory,<br />
&nbsp; &nbsp; &nbsp; &nbsp; Name: "MyService",<br />
&nbsp; &nbsp; &nbsp; &nbsp; DisplayName: "My Service",<br />
&nbsp; &nbsp; &nbsp; &nbsp; LongDescription: "My Service provides support for...",<br />
&nbsp; &nbsp; &nbsp; &nbsp; LogLocation: _Straps.Strap("baseFilePath"),<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; Init: InitService,<br />
&nbsp; &nbsp; &nbsp; &nbsp; Start: StartService,<br />
&nbsp; &nbsp; &nbsp; &nbsp; Stop: StopService,<br />
&nbsp; &nbsp; }<br />
<br />
&nbsp; &nbsp; // Run any command line options or start the service<br />
&nbsp; &nbsp; config.Run()<br />
}<br />
<br />
func InitService() {<br />
&nbsp; &nbsp; fmt.Println("Service Inited")<br />
}<br />
<br />
func StartService() {<br />
&nbsp; &nbsp; fmt.Println("Service Started")<br />
}<br />
<br />
func StopService() {<br />
&nbsp; &nbsp; fmt.Println("Service Stopped")<br />
}</div>
<br />
The Init, Start and Stop functions must return control back to the config.Run function.<br />
<br />
The code I have has been tested with the Mac OS. The code for linux is&nbsp;identical except for the script that needs to be created and installed. Also the implementation for Start and Stop uses different programs. In the near future I will test the Linux portion of the code. The Window portion requires some refactoring and will not build. If you plan to use Windows start with Daniel's code.<br />
<br />
Once you build the code, open a Terminal session where the binary has been created and run the different commands.<br />
<br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
./MyService debug<br />
<br />
./MyService install<br />
<br />
./MyService start<br />
<br />
./MyService stop</div>
<br />
As always I hope the code helps you create and run your own services.
