无法将Go应用程序exe作为Windows服务启动。

huangapple go评论81阅读模式
英文:

Cannot start a Go application exe as a windows services

问题

我有一个使用Go语言作为后端的应用程序。
我可以使用以下命令使用sc和nssm创建一个服务:
sc create TestService binpath=C:\User\sds\Desktop\test.exe nssm install TestService C:\User\sds\Desktop\test.exe

服务已成功创建,但无法启动。在启动服务时出现了启动超时错误

我需要从Windows服务中启动该应用程序。

提前感谢。

英文:

I have a application with Go language as the backend.
I can create a service using the sc and nssm as below :
sc create TestService binpath=C:\User\sds\Desktop\test.exe
nssm install TestService C:\User\sds\Desktop\test.exe

The services are created successfully but it doesn not get started. It gives startup timeout error while starting the service.

I need to start the application from windows services.

Thanks in advance.

答案1

得分: 18

Go语言有一个用于在Windows中创建服务的库。
请检查这个库 github.com/kardianos/service

package main

import (
	"log"

	"github.com/kardianos/service"
)

var logger service.Logger

type program struct{}

func (p *program) Start(s service.Service) error {
	// Start should not block. Do the actual work async.
	go p.run()
	return nil
}

func (p *program) run() {
	// Do work here
}

func (p *program) Stop(s service.Service) error {
	// Stop should not block. Return with a few seconds.
	return nil
}

func main() {
	svcConfig := &service.Config{
		Name:        "GoServiceExampleSimple",
		DisplayName: "Go Service Example",
		Description: "This is an example Go service.",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	logger, err = s.Logger(nil)
	if err != nil {
		log.Fatal(err)
	}
	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}
英文:

Go has a library for creating services in windows.
Please check this library github.com/kardianos/service.

package main

import (
	"log"

	"github.com/kardianos/service"
)

var logger service.Logger

type program struct{}

func (p *program) Start(s service.Service) error {
	// Start should not block. Do the actual work async.
	go p.run()
	return nil
}
func (p *program) run() {
	// Do work here
}
func (p *program) Stop(s service.Service) error {
	// Stop should not block. Return with a few seconds.
	return nil
}

func main() {
	svcConfig := &service.Config{
		Name:        "GoServiceExampleSimple",
		DisplayName: "Go Service Example",
		Description: "This is an example Go service.",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	logger, err = s.Logger(nil)
	if err != nil {
		log.Fatal(err)
	}
	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}

huangapple
  • 本文由 发表于 2016年2月24日 22:44:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/35605238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定