开发者们大家好,我已经有一段时间没有写一些 Windows 风格的东西了。所以,今天我想指导大家如何用 Go 编写 Windows 服务应用程序。是的,你没有听错,就是go语言。在本教程博客中,我们将介绍有关 Windows 服务应用程序的一些基本内容,在后面的部分中,我将指导您完成一个简单的代码演练,我们为 Windows 服务编写代码,将一些信息记录到文件中。话不多说,让我们开始吧...!
Windows 服务应用程序又名 Windows 服务是在后台运行的小型应用程序。与普通的 Windows 应用程序不同,它们没有 GUI 或任何形式的用户界面。这些服务应用程序在计算机启动时开始运行。无论它在哪个用户帐户中运行,它都会运行。它的生命周期(启动、停止、暂停、继续等)由名为服务控制管理器 (SCM) 的程序控制。
因此,从这里我们可以理解,我们应该以这样的方式编写我们的 Windows Service,以便 SCM 应该与我们的 Windows Service 交互并管理它的生命周期。
您可以考虑使用 Go 来编写 Windows 服务的几个因素。
Go 的并发模型允许更快且资源高效的处理。 Go 的 goroutine 允许我们编写可以执行多任务处理而不会出现任何阻塞或死锁的应用程序。
传统上,Windows 服务是使用 C++ 或 C(有时是 C#)编写的,这不仅导致代码复杂,而且 DX(开发人员体验)很差。 Go 对 Windows 服务的实现非常简单,每一行代码都有意义.
你可能会问,“为什么不使用像Python这样更简单的语言呢?”。原因是Python 的解释性质。 Go 编译为静态链接的单个文件二进制文件,这对于 Windows 服务高效运行至关重要。 Go 二进制文件不需要任何运行时/解释器。 Go代码也可以交叉编译。
虽然 Go 是一种垃圾收集语言,但它为与低级元素交互提供了坚实的支持。我们可以在go中轻松调用win32 API和通用系统调用。
好吧,信息足够了。让我们编码...
此代码演练假设您具有 Go 语法的基本知识。如果没有,A Tour of Go 将是一个学习 Go 的好地方。
注意:此软件包还包含对基于 UNIX 的操作系统(如 Mac OS 和 Linux)的操作系统级 go 语言支持。
创建一个main.go文件。 main.go 文件包含 main 函数,它充当我们的 Go 应用程序/服务的入口点。
为了创建服务实例,我们需要编写一个名为Service Context的东西,它实现了 golang.org/x/sys/windows/svc 的 Handler 接口。
所以,接口定义看起来像这样
Execute 函数会在服务启动时被包代码调用,一旦 Execute 完成,服务就会退出。
我们从仅接收通道 r 读取服务变更请求并采取相应行动。我们还应该通过向仅发送通道发送信号来更新我们的服务。我们可以将可选参数传递给 args 参数。
退出时,我们可以返回 exitCode 为 0 的成功执行。我们还可以使用 svcSpecificEC 来实现这一点。
创建一个常量,其中包含我们的服务可以从 SCM 接受的信号。
const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue
Our main goal is the log some data every 30 seconds. So we need to define a thread safe timer for that.
tick := time.Tick(30 * time.Second)
So, we have done all the initialization stuffs. It's time to send START signal to the SCM. we're going to do exactly that,
status <- svc.Status{State: svc.StartPending} status <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
Now we're going to write a loop which acts as amainloopfor our application. Handling events in loop makes our application never ending and we can break the loop only when the SCM sends STOP or SHUTDOWN signal.
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) } } }
Here we used a select statement to receive signals from channels. In first case, we handle the Timer's tick signal. This case receives signal every 30 seconds, as we declared before. We log a string "Tick Handled...!" in this case.
Secondly, we handle the signals from SCM via the receive-only r channel. So, we assign the value of the signal from r to a variable c and using a switch statement, we can handle all the lifecycle event/signals of our service. We can see about each lifecycle below,
So, when on receiving either svc.Stop or svc.Shutdown signal, we break the loop. It is to be noted that we need to send STOP signal to the SCM to let the SCM know that our service is stopping.
status <- svc.Status{State: svc.StopPending} return false, 1
Note: It's super hard to debug Windows Service Applications when running on Service Control Mode. That's why we are writing an additional Debug mode.
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 debug mode.") } } }
func main() { f, err := os.OpenFile("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) //change to true to run in debug mode }
Note: We are logging the logs to a log file. In advanced scenarios, we log our logs to Windows Event Logger. (phew, that sounds like a tongue twister ?)
PS C:\> go build -ldflags "-s -w"
For installing, deleting, starting and stopping our service, we use an inbuilt tool called sc.exe
To install our service, run the following command in powershellas Administrator,
PS C:\> sc.exe create MyService
To start our service, run the following command,
PS C:\> sc.exe start MyService
To delete our service, run the following command,
PS C:\> sc.exe delete MyService
You can explore more commands, just type sc.exe without any arguments to see the available commands.
As we can see, implementing Windows Services in go is straightforward and requires minimal implementation. You can write your own windows services which acts as a web server and more. Thanks for reading and don't forget to drop a ❤️.
Here is the complete code for your reference.
// 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 debug 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) }
以上是用 Go 编写 Windows 服务的详细内容。更多信息请关注PHP中文网其他相关文章!