golang实现注册系统服务(Windows、Darwin)

2023-12-20 13:52

本文主要是介绍golang实现注册系统服务(Windows、Darwin),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

golang实现注册系统服务(Windows、Darwin)

仓库地址:https://github.com/ziyifast/yiSystemService

使用第三方包:go get “github.com/kardianos/service”
日志库:go get “github.com/sirupsen/logrus”

  • log “github.com/sirupsen/logrus”

1 初始化日志

util/log.go:

package utilimport (log "github.com/sirupsen/logrus""io""os"
)func InitLog(logPath string) {//设置输出样式,自带的只有两种样式logrus.JSONFormatter{}和logrus.TextFormatter{}log.SetFormatter(&log.TextFormatter{})log.SetOutput(os.Stdout)//设置output,默认为stderr,可以为任何io.Writer,比如文件*os.Filefile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)writers := []io.Writer{file,os.Stdout}//同时写文件和屏幕fileAndStdoutWriter := io.MultiWriter(writers...)if err == nil {log.SetOutput(fileAndStdoutWriter)} else {log.Info("failed to log to file.")}//设置最低loglevellog.SetLevel(log.InfoLevel)
}

2 导入三方Service库+编写serviceConfig(描述、可执行文件路径等)

2.1 consts

①consts/consts.go:

package constsimport "path"const (ServiceVersion     = "v1.0"ServiceName        = "yiService"ServicePort        = 9999ServiceDisplayName = "yi.service"ServiceDescription = "my test service"
)var LogPath stringfunc init() {LogPath = path.Join(WorkDir, "yiService.log")
}

②consts/consts_darwin.go:

//go:build darwin
// +build darwinpackage constsimport "path/filepath"var (StartupBash  = filepath.Join(WorkDir, "startup.sh")ShutdownBash = filepath.Join(WorkDir, "shutdown.sh")
)const (WorkDir = "/usr/local/yiService"MainExe = "yiService"
)    

③consts/consts_windows.go:

package constsimport "path/filepath"var (StartupBash  = filepath.Join(WorkDir, "startup.bat")ShutdownBash = filepath.Join(WorkDir, "shutdown.bat")
)const (WorkDir    = "c:/yiService"MainExe    = "yiService.exe"
)

2.2 system_service

system_service/system_service.go:

package system_serviceimport ("awesomeProject1/consts""fmt""github.com/kardianos/service"log "github.com/sirupsen/logrus""os""runtime"
)var (logger service.Loggersvc    service.Service
)func init() {svcConfig := &service.Config{Name:             consts.ServiceName,WorkingDirectory: consts.WorkDir,DisplayName:      consts.ServiceDisplayName,Description:      consts.ServiceDescription,Arguments:        []string{"service", "run"}, //服务注册成功之后,由服务去执行yiService.exe service run【运行服务】Executable:       fmt.Sprintf("%s/%s", consts.WorkDir, consts.ServiceName),Option:           service.KeyValue{},}if runtime.GOOS == "windows" {svcConfig.Executable = fmt.Sprintf("%s\\%s.exe", consts.WorkDir, consts.ServiceName)}var err errorprogram := &Program{}svc, err = service.New(program, svcConfig)if err != nil {log.Errorf("create service fail %v\n", err)return}errChan := make(chan error, 5)logger, err = svc.Logger(errChan)if err != nil {log.Errorf("%v\n", err)return}if err != nil {log.Errorf("%v\n", err)return}go func() {log.Info("watching err chan....")for {err := <-errChanif err != nil {log.Fatalf("service err %v", err)}}}()
}func StartSVC() {log.Infof("StartSVC...")serviceControl("install")serviceControl("start")
}func StopSVC() {log.Infof("try to stop service, if already exists.")serviceControl("stop")
}func RunSVC() {fmt.Sprintf("%s service running \n", runtime.GOOS)if err := svc.Run(); err != nil {fmt.Sprintf("%s service running fail %v \n", runtime.GOOS, err)os.Exit(1)}
}func serviceControl(action string) {log.Infof("%s service %s \n", runtime.GOOS, action)if err := service.Control(svc, action); err != nil {log.Infof("%s service: %v \n", action, err)}
}

3 编写服务脚本(startup、shutdown脚本)

3.1 startup脚本

  1. assets/startup.bat.tmpl
@echo off@REM It is recommended to start here.
@REM Modify bash args below.
@REM "name" and "tags" must be alphanumeric sequence: [a-zA-Z-_.]
@REM Chinese chars are not supported here in bash file.
@REM
@REM Example:
@REM
@REM yiService.exe service start ^
@REM
@REM Startup from here
@REM
c:/yiService/yiService.exe service startecho "yiService started!"
echo ""
pause
  1. assets/startup.sh.tmpl
#!/bin/bash# It is recommended to start here.
# Modify bash args below.
# "name" and "tags" must be alphanumeric sequence: [a-zA-Z-_.]
# Chinese chars are not supported here in bash file.
#
# Example:
#
# yiService.exe service start \
#
# Startup from here
#
# launchctl start yiService
./yiService service startecho yiService started!
ps aux |grep yiService
echo ""

3.2 shutdown脚本

  1. assets/shutdown.bat.tmpl
@echo off
@REM This command bash will stop the yiService windows service
@REM And then uninstall this service from operation system
@REM Configurations will be remained in directory c:/yiService/yiService on the disk.
@REM You can restart from those configurations in the near future.
@REM
c:/yiService/yiService.exe service stop
set "$process=yiService.exe"
for %%a in (%$process%) do tasklist /fi "imagename eq %%a"  | find "%%a" && taskkill /f /im %%aecho shutdown yiService successfully!
pause
  1. assets/shutdown.sh.tmpl
#!/bin/bash# This command bash will stop the yiService windows service
# And then uninstall this service from operation system
# Configurations will be remained in directory c:/yiService on the disk.
# You can restart from those configurations in the near future.
#./yiService service stop
PID=$(ps -eaf | grep '/usr/local/yiService' | grep -v grep | awk '{print $2}')
if [[ "" !=  "$PID" ]]; thenecho "killing $PID"kill -9 "$PID"
fiecho shutdown yiService successfully!

4 编写extractFiles(执行exe文件之后,拷贝exe到服务工作目录)

system_service/extract_files.go:

package system_serviceimport ("awesomeProject1/assets""awesomeProject1/consts""fmt"log "github.com/sirupsen/logrus""io""os""runtime"
)func ExtractFiles() {CopyMainExe()//copy startup\shutdownif err := os.WriteFile(consts.StartupBash, assets.StartupBatTmpl, os.ModePerm); err != nil {log.Errorf("create startup bash failed %v", err)}if err := os.WriteFile(consts.ShutdownBash, assets.ShutdownBatTmpl, os.ModePerm); err != nil {log.Errorf("create shutdown bash failed %v", err)}
}func CopyMainExe() {executable, err := os.Executable()log.Infof("install %s to %s", executable, consts.MainExe)if err != nil {log.Errorf("%v", err)}sFile, err := os.Open(executable)if err != nil {log.Errorf("%v", err)}defer sFile.Close()exePath := fmt.Sprintf("%s/%s", consts.WorkDir, consts.MainExe)if runtime.GOOS == "windows" {exePath = fmt.Sprintf("%s\\%s", consts.WorkDir, consts.MainExe)}_, err = os.Stat(exePath)if err == nil {//overwriteif err := os.RemoveAll(exePath); err != nil {log.Errorf("%v", err)}}eFile, err := os.Create(exePath)if err != nil {log.Errorf("%v", err)}defer eFile.Close()if _, err = io.Copy(eFile, sFile); err != nil {log.Errorf("%v", err)}if err = eFile.Sync(); err != nil {log.Errorf("%v", err)}if err = os.Chdir(consts.WorkDir); err != nil {log.Errorf("%v\n", err)}if err = os.Chmod(consts.MainExe, os.FileMode(0777)); err != nil {log.Errorf("%v", err)}
}

5 编写firewall部分+main函数部分(开放端口+由系统服务拉起进程)

firewall部分:以管理员身份运行,开放进程服务端口
cmd/main.go部分:初次运行尝试卸载服务,带os.Args参数运行启动服务

5.1 firewall部分

  1. darwin

system_service/firewall/firewall_darwin.go:

//go:build darwin
// +build darwinpackage firewallimport ("awesomeProject1/consts""bytes""fmt"log "github.com/sirupsen/logrus""os/exec""strconv""strings"
)func OpenPort() {log.Infof("darwin firewall checking\n")cmd0 := exec.Command("/usr/bin/nc", "-z", "127.0.0.1", fmt.Sprintf("%d", consts.ServicePort))log.Warnf("cmd0=%s\n", cmd0)stdout, err := cmd0.CombinedOutput()result := string(stdout)if err != nil {log.Infof("err=%v \n", err)return}if strings.Contains(result, "command not found") {fmt.Println("[warn]:", result)return}if strings.Contains(result, "not running") {fmt.Println("[warn]:", result)return}if strings.Contains(result, strconv.Itoa(consts.ServicePort)) {log.Warnf("%d already opened\n", consts.ServicePort)return}cmd := exec.Command("bash", "-c", fmt.Sprintf("firewall-cmd --zone=public --add-port=%d/tcp --permanent && firewall-cmd --reload", consts.ServicePort))var out bytes.Buffervar stderr bytes.Buffercmd.Stdout = &outcmd.Stderr = &stderrif err := cmd.Run(); err != nil {log.Warnf("%s", stderr.String())log.Warnf("%v", err)}log.Warnf(out.String())
}
  1. Windows
    system_service/firewall/firewall_windows.go
//go:build windows
// +build windowspackage firewallimport ("bytes""fmt"log "github.com/sirupsen/logrus""os/exec""runtime"
)func OpenPort() {log.Infot("windows firewall checking")cmd := exec.Command("cmd", "/c", "netsh advfirewall firewall delete rule name=\"yiService\"")var out bytes.Buffervar stderr bytes.Buffercmd.Stdout = &outcmd.Stderr = &stderrif runtime.GOOS == "windows" {}if err := cmd.Run(); err != nil {log.Errorf("%s", stderr.String())log.Errorf("%v", err)}cmd2 := exec.Command("cmd", "/c",fmt.Sprintf("netsh advfirewall firewall add rule name=\"yiService\" dir=in action=allow protocol=TCP localport=%d",consts.ServicePort,))var out2 bytes.Buffervar stderr2 bytes.Buffercmd2.Stdout = &out2cmd2.Stderr = &stderr2if runtime.GOOS == "windows" {}if err := cmd2.Run(); err != nil {log.Errorf("%s", stderr2.String())log.Errorf("%v", err)}
}

5.2 main函数

cmd/main.go

package mainimport ("awesomeProject1/consts""awesomeProject1/system_service""awesomeProject1/system_service/firewall""awesomeProject1/util"log "github.com/sirupsen/logrus""os"
)func init() {//os.Setenv("dev", "true")util.InitLog(consts.LogPath)
}func main() {if len(os.Getenv("dev")) != 0 {system_service.StopSVC()firewall.OpenPort()system_service.StartSVC()system_service.RunSVC()}log.Errorf("os.Args=%v len=%v \n", os.Args, len(os.Args))if len(os.Args) == 1 {//stop svc if existsystem_service.StopSVC()log.Errorf("install %v \n", consts.ServiceName)if err := os.MkdirAll(consts.WorkDir, os.ModePerm); err != nil {log.Errorf("%v\n", err)}firewall.OpenPort()system_service.ExtractFiles()pwd, err := os.Getwd()if err != nil {log.Errorf("%v\n", err)}log.Infof("install svc, working directory %s", pwd)system_service.StartSVC()log.Infof("yiService installed!")return}os.Chdir(consts.WorkDir)log.Errorf("service %s \n", os.Args[2])switch os.Args[2] {case "start":system_service.StartSVC()returncase "stop":system_service.StopSVC()returndefault:system_service.RunSVC()log.Info("running yiService")}
}

这篇关于golang实现注册系统服务(Windows、Darwin)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/516289

相关文章

利用Python实现可回滚方案的示例代码

《利用Python实现可回滚方案的示例代码》很多项目翻车不是因为不会做,而是走错了方向却没法回头,技术选型失败的风险我们都清楚,但真正能提前规划“回滚方案”的人不多,本文从实际项目出发,教你如何用Py... 目录描述题解答案(核心思路)题解代码分析第一步:抽象缓存接口第二步:实现两个版本第三步:根据 Fea

Go语言使用slices包轻松实现排序功能

《Go语言使用slices包轻松实现排序功能》在Go语言开发中,对数据进行排序是常见的需求,Go1.18版本引入的slices包提供了简洁高效的排序解决方案,支持内置类型和用户自定义类型的排序操作,本... 目录一、内置类型排序:字符串与整数的应用1. 字符串切片排序2. 整数切片排序二、检查切片排序状态:

python利用backoff实现异常自动重试详解

《python利用backoff实现异常自动重试详解》backoff是一个用于实现重试机制的Python库,通过指数退避或其他策略自动重试失败的操作,下面小编就来和大家详细讲讲如何利用backoff实... 目录1. backoff 库简介2. on_exception 装饰器的原理2.1 核心逻辑2.2

Java实现视频格式转换的完整指南

《Java实现视频格式转换的完整指南》在Java中实现视频格式的转换,通常需要借助第三方工具或库,因为视频的编解码操作复杂且性能需求较高,以下是实现视频格式转换的常用方法和步骤,需要的朋友可以参考下... 目录核心思路方法一:通过调用 FFmpeg 命令步骤示例代码说明优点方法二:使用 Jaffree(FF

基于C#实现MQTT通信实战

《基于C#实现MQTT通信实战》MQTT消息队列遥测传输,在物联网领域应用的很广泛,它是基于Publish/Subscribe模式,具有简单易用,支持QoS,传输效率高的特点,下面我们就来看看C#实现... 目录1、连接主机2、订阅消息3、发布消息MQTT(Message Queueing Telemetr

Java实现图片淡入淡出效果

《Java实现图片淡入淡出效果》在现代图形用户界面和游戏开发中,**图片淡入淡出(FadeIn/Out)**是一种常见且实用的视觉过渡效果,它可以用于启动画面、场景切换、轮播图、提示框弹出等场景,通过... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细

Python实现获取带合并单元格的表格数据

《Python实现获取带合并单元格的表格数据》由于在日常运维中经常出现一些合并单元格的表格,如果要获取数据比较麻烦,所以本文我们就来聊聊如何使用Python实现获取带合并单元格的表格数据吧... 由于在日常运维中经常出现一些合并单元格的表格,如果要获取数据比较麻烦,现将将封装成类,并通过调用list_exc

使用animation.css库快速实现CSS3旋转动画效果

《使用animation.css库快速实现CSS3旋转动画效果》随着Web技术的不断发展,动画效果已经成为了网页设计中不可或缺的一部分,本文将深入探讨animation.css的工作原理,如何使用以及... 目录1. css3动画技术简介2. animation.css库介绍2.1 animation.cs

Java进行日期解析与格式化的实现代码

《Java进行日期解析与格式化的实现代码》使用Java搭配ApacheCommonsLang3和Natty库,可以实现灵活高效的日期解析与格式化,本文将通过相关示例为大家讲讲具体的实践操作,需要的可以... 目录一、背景二、依赖介绍1. Apache Commons Lang32. Natty三、核心实现代

SpringBoot实现接口数据加解密的三种实战方案

《SpringBoot实现接口数据加解密的三种实战方案》在金融支付、用户隐私信息传输等场景中,接口数据若以明文传输,极易被中间人攻击窃取,SpringBoot提供了多种优雅的加解密实现方案,本文将从原... 目录一、为什么需要接口数据加解密?二、核心加解密算法选择1. 对称加密(AES)2. 非对称加密(R