Created
September 9, 2024 08:03
-
-
Save parsibox/a512373c43df43ee0a8d8d1baa53d55c to your computer and use it in GitHub Desktop.
go windows service
This file contains hidden or 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
go build -ldflags "-s -w" | |
PS C:\> sc.exe create MyService <path to your service_app.exe> | |
PS C:\> sc.exe start MyService | |
PS C:\> sc.exe delete MyService | |
// file: main.go | |
package main | |
import ( | |
"fmt" | |
"golang.org/x/sys/windows/svc" | |
"golang.org/x/sys/windows/svc/debug" | |
"log" | |
"os" | |
"time" | |
) | |
type myService struct{} | |
func (m *myService) Execute(args []string, r <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) { | |
const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue | |
tick := time.Tick(5 * time.Second) | |
status <- svc.Status{State: svc.StartPending} | |
status <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} | |
loop: | |
for { | |
select { | |
case <-tick: | |
log.Print("Tick Handled...!") | |
case c := <-r: | |
switch c.Cmd { | |
case svc.Interrogate: | |
status <- c.CurrentStatus | |
case svc.Stop, svc.Shutdown: | |
log.Print("Shutting service...!") | |
break loop | |
case svc.Pause: | |
status <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted} | |
case svc.Continue: | |
status <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} | |
default: | |
log.Printf("Unexpected service control request #%d", c) | |
} | |
} | |
} | |
status <- svc.Status{State: svc.StopPending} | |
return false, 1 | |
} | |
func runService(name string, isDebug bool) { | |
if isDebug { | |
err := debug.Run(name, &myService{}) | |
if err != nil { | |
log.Fatalln("Error running service in debug mode.") | |
} | |
} else { | |
err := svc.Run(name, &myService{}) | |
if err != nil { | |
log.Fatalln("Error running service in Service Control mode.") | |
} | |
} | |
} | |
func main() { | |
f, err := os.OpenFile("E:/awesomeProject/debug.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) | |
if err != nil { | |
log.Fatalln(fmt.Errorf("error opening file: %v", err)) | |
} | |
defer f.Close() | |
log.SetOutput(f) | |
runService("myservice", false) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment