gpt4 book ai didi

go - 通过服务运行 go app

转载 作者:IT王子 更新时间:2023-10-29 02:22:49 24 4
gpt4 key购买 nike

在 CentOS 6.8 中,我有一个 golang 应用程序,它在命令 go run main.go 中运行,我需要创建一个系统服务以在启动时像服务 httpd 一样运行它。
我知道我必须创建类似 /etc/rc.d/init.d/httpd 的文件,但我不知道如何执行该命令。

最佳答案

首先,您需要构建您的 Go 二进制文件并将其放入您的路径中。

go install main.go

如果您的“主”文件名为 main,go install 将在您的路径中放置一个名为“main”的二进制文件,因此我建议您将文件重命名为您对项目/服务器的名称。

mv main.go coolserver.go
go install coolserver.go

您可以运行 coolserver 以确保一切正常。如果你的 $GOPATH 设置正确,它就会。

这是一个名为 service.sh 的 init.d 服务示例

#!/bin/sh
### BEGIN INIT INFO
# Provides: <NAME>
# Required-Start: $local_fs $network $named $time $syslog
# Required-Stop: $local_fs $network $named $time $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: <DESCRIPTION>
### END INIT INFO

SCRIPT=<COMMAND>
FLAGS="--auth=user:password"
RUNAS=<USERNAME>

PIDFILE=/var/run/<NAME>.pid
LOGFILE=/var/log/<NAME>.log

start() {
if [ -f /var/run/$PIDNAME ] && kill -0 $(cat /var/run/$PIDNAME); then
echo 'Service already running' >&2
return 1
fi
echo 'Starting service…' >&2
local CMD="$SCRIPT $FLAGS &> \"$LOGFILE\" & echo \$!"
su -c "$CMD" $RUNAS > "$PIDFILE"
echo 'Service started' >&2
}

stop() {
if [ ! -f "$PIDFILE" ] || ! kill -0 $(cat "$PIDFILE"); then
echo 'Service not running' >&2
return 1
fi
echo 'Stopping service…' >&2
kill -15 $(cat "$PIDFILE") && rm -f "$PIDFILE"
echo 'Service stopped' >&2
}

uninstall() {
echo -n "Are you really sure you want to uninstall this service? That cannot be undone. [yes|No] "
local SURE
read SURE
if [ "$SURE" = "yes" ]; then
stop
rm -f "$PIDFILE"
echo "Notice: log file is not be removed: '$LOGFILE'" >&2
update-rc.d -f <NAME> remove
rm -fv "$0"
fi
}

case "$1" in
start)
start
;;
stop)
stop
;;
uninstall)
uninstall
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart|uninstall}"
esac

复制到/etc/init.d:​​

cp "service.sh" "/etc/init.d/coolserver"
chmod +x /etc/init.d/coolserver

记得替换

<NAME> = coolserver
<DESCRIPTION> = Describe your service here (be concise)
<COMMAND> = /path/to/coolserver
<USER> = Login of the system user the script should be run as

启动并测试您的服务并安装要在启动时运行的服务:

service coolserver start
service coolserver stop
update-rc.d coolserver defaults

关于go - 通过服务运行 go app,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39348993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com