golang.org/x/sys@v0.20.1-0.20240517151509-673e0f94c16d/windows/svc/example/main.go (about) 1 // Copyright 2012 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build windows 6 7 // Example service program that beeps. 8 // 9 // The program demonstrates how to create Windows service and 10 // install / remove it on a computer. It also shows how to 11 // stop / start / pause / continue any service, and how to 12 // write to event log. It also shows how to use debug 13 // facilities available in debug package. 14 package main 15 16 import ( 17 "flag" 18 "fmt" 19 "log" 20 "os" 21 "strings" 22 23 "golang.org/x/sys/windows/svc" 24 ) 25 26 func usage(errmsg string) { 27 fmt.Fprintf(os.Stderr, 28 "%s\n\n"+ 29 "usage: %s <command>\n"+ 30 " where <command> is one of\n"+ 31 " install, remove, debug, start, stop, pause or continue.\n", 32 errmsg, os.Args[0]) 33 os.Exit(2) 34 } 35 36 var svcName = "exampleservice" 37 38 func main() { 39 flag.StringVar(&svcName, "name", svcName, "name of the service") 40 flag.Parse() 41 42 inService, err := svc.IsWindowsService() 43 if err != nil { 44 log.Fatalf("failed to determine if we are running in service: %v", err) 45 } 46 if inService { 47 runService(svcName, false) 48 return 49 } 50 51 if len(os.Args) < 2 { 52 usage("no command specified") 53 } 54 55 cmd := strings.ToLower(os.Args[1]) 56 switch cmd { 57 case "debug": 58 runService(svcName, true) 59 return 60 case "install": 61 err = installService(svcName, "example service") 62 case "remove": 63 err = removeService(svcName) 64 case "start": 65 err = startService(svcName) 66 case "stop": 67 err = controlService(svcName, svc.Stop, svc.Stopped) 68 case "pause": 69 err = controlService(svcName, svc.Pause, svc.Paused) 70 case "continue": 71 err = controlService(svcName, svc.Continue, svc.Running) 72 default: 73 usage(fmt.Sprintf("invalid command %s", cmd)) 74 } 75 if err != nil { 76 log.Fatalf("failed to %s %s: %v", cmd, svcName, err) 77 } 78 return 79 }