注册服务,注意这里的 Service name 需要根据代码内部写的服务名称设置(如下 go 代码中的serviceName=GoHttpService),否则无法成功注册服务, Failure Operation可以设置服务被关闭后的操作(自动重启等)
package main
import (
"fmt"
"log"
"net/http"
"golang.org/x/sys/windows/svc"
)
var serviceName = "GoHttpService"
type myService struct{}
func (m *myService) Execute(args []string, r <-chan svc.ChangeRequest, s chan<- svc.Status) (svcSpecificEC bool, exitCode uint32) {
const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown
s <- svc.Status{State: svc.StartPending}
go runHttpServer()
s <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
for {
c := <-r
switch c.Cmd {
case svc.Stop, svc.Shutdown:
log.Println("Service is stopping...")
s <- svc.Status{State: svc.StopPending}
return
default:
continue
}
}
}
func runHttpServer() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
port := "8082"
log.Printf("Server starting on port %s\n", port)
if err := http.ListenAndServe("0.0.0.0:"+port, nil); err != nil {
log.Fatal("ListenAndServe error: ", err)
}
}
func main() {
inService, err := svc.IsWindowsService()
if err != nil {
log.Fatalf("Failed to determine if we are running in service: %v", err)
}
if inService {
run := svc.Run
if err := run(serviceName, &myService{}); err != nil {
log.Fatalf("Failed to run service: %v", err)
}
} else {
runHttpServer()
}
}