package main import ( "fmt" "github.com/shirou/gopsutil/winservices" "golang.org/x/sys/windows/svc/mgr" "log" ) func main() { s, err := NewWinService("GWY20_Mysql") // s, err := NewWinService("GWY20_Tomcat") // s, err := NewWinService("nginx") if s == nil || err != nil { log.Print("发生异常:", err) return } err = s.StartService() if err != nil { log.Print("启动异常:", err) } else { log.Print("启动成功!") } } // 启动一个服务 func (s *Service) StartService() error { return StartService(s.Name) } // 启动一个服务 func StartService(name string) error { m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(name) if err != nil { return fmt.Errorf("could not access service: %v", err) } defer s.Close() err = s.Start("is", "manual-started") if err != nil { return fmt.Errorf("could not start service: %v", err) } return nil } // 新建一个Service对象 func NewWinService(serviceName string) (*Service, error) { winService, err := winservices.NewService(serviceName) if err != nil { return nil, err } result := &Service{ Name: serviceName, srv: winService, } log.Print("测试问题:", result) err = result.getServiceDetail() return result, err } // 定义Service对象 type Service struct { Name string srv *winservices.Service Config mgr.Config Status winservices.ServiceStatus } // 得到Service信息 func (s *Service) getServiceDetail() error { defer func() { if err := recover(); err != nil { return } }() err := s.srv.GetServiceDetail() if err != nil { // 服务打开失败 return err } s.Name = s.srv.Name s.Status = s.srv.Status s.Config = s.srv.Config return nil }