使用Golang编写Windows服务
主要是使用”github.com/kardianos/service“这个库
它已经处理好了与服务管理器的交互细节,并且自带服务安装、卸载、启动、停止等功能,非常齐全了。
直接上完整代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | package main import ( "log" "os" "syscall" "time" "unsafe" "github.com/kardianos/service" ) var ( kernel32DLL = syscall.NewLazyDLL( "kernel32.dll" ) outputDebugString = kernel32DLL.NewProc( "OutputDebugStringW" ) ) func OutputDebugString(message string) { strPtr, _ := syscall.UTF16PtrFromString(message) outputDebugString.Call(uintptr(unsafe.Pointer(strPtr))) } // MyService 实现了 service.Service 接口 type MyService struct {} func (m *MyService) Start(s service.Service) error { go m.run() return nil } func (m *MyService) run() { OutputDebugString( "Service start..." ) // 在这里编写你的服务逻辑 for { OutputDebugString( "Service is running..." ) time.Sleep(1 * time.Second) } } func (m *MyService) Stop(s service.Service) error { // 停止服务的逻辑 OutputDebugString( "Service exit..." ) return nil } func main() { OutputDebugString( "main starting..." ) // 服务的名称、显示名称和描述 svcConfig := &service.Config{ Name: "MyGoService" , DisplayName: "My Golang Service" , Description: "This is a sample service by golang." , } prg := &MyService{} s, err := service.New(prg, svcConfig) if err != nil { log.Fatal(err) } // 如果服务已经安装,可以通过以下命令来启动、停止、重启或卸载服务: // service.exe install // service.exe start // service.exe stop // service.exe restart // service.exe uninstall // 通过以下代码来控制服务的启动和停止 if len(os.Args) > 1 { err = service.Control(s, os.Args[1]) if err != nil { log.Fatal(err) } return } err = s.Run() if err != nil { log.Fatal(err) } } |
编译完成后生成servicedemo.exe,然后直接执行以下命令进行安装:
1 | servicedemo.exe install |
然后在服务管理器中就可以看到服务了:
然后直接在服务管理器中启动或使用命令行”servicedemo.exe start“启动就可以了。
在服务中我使用OutputDebugString打印调试信息,所以打开DebugView就可以看到启动和停止的信息。
停止服务使用 "servicedemo.exe stop"
卸载服务使用"servicedemo.exe uninstall"
就是这么简单!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· PPT革命!DeepSeek+Kimi=N小时工作5分钟完成?
· What?废柴, 还在本地部署DeepSeek吗?Are you kidding?
· 赶AI大潮:在VSCode中使用DeepSeek及近百种模型的极简方法
· DeepSeek企业级部署实战指南:从服务器选型到Dify私有化落地