Created
December 20, 2018 11:05
-
-
Save vsg24/069c003a10ff60d2b1343dcce75c269c to your computer and use it in GitHub Desktop.
How to install Go app as a Windows service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/kardianos/service" | |
"log" | |
"os" | |
"time" | |
) | |
var logger service.Logger | |
type program struct{} | |
func (p *program) Start(s service.Service) error { | |
// Start should not block. Do the actual work async. | |
fmt.Println(time.Now().Format("2006-01-02 03:04:05 PM"), "Service started") | |
go p.run() | |
return nil | |
} | |
func (p *program) run() { | |
// Do work here | |
// start/initialize your server or something else | |
} | |
func (p *program) Stop(s service.Service) error { | |
// Stop should not block. Return with a few seconds. | |
return nil | |
} | |
func main() { | |
svcConfig := &service.Config{ | |
Name: "UniqueServiceName", | |
DisplayName: "My Service", | |
Description: "This is the service.", | |
} | |
prg := &program{} | |
s, err := service.New(prg, svcConfig) | |
if err != nil { | |
log.Fatal(err) | |
} | |
logger, err = s.Logger(nil) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// read command line args | |
var argsWithoutProgName = os.Args[1:] | |
for _, param := range argsWithoutProgName { | |
if param == "install" { | |
err = s.Install() | |
if err != nil { | |
logger.Error(err) | |
} else { | |
fmt.Println("Service installed successfully.") | |
} | |
} else if param == "uninstall" { | |
err = s.Uninstall() | |
if err != nil { | |
logger.Error(err) | |
} else { | |
fmt.Println("Service uninstalled successfully.") | |
} | |
} | |
} | |
err = s.Run() | |
if err != nil { | |
logger.Error(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment