将应用程序制作成服务启动
1、编写一个简单的服务
package main
import (
"net/http"
)
func main() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world!"))
})
http.ListenAndServe(":8090", nil)
}
2、制作makefile进行编译
# 命令必须以tab键开头
linux:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o server server.go
mac:
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -o server server.go
windows:
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o server server.go
$ make linux
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o server server.go
$ mkdir -p /opt/myserver
$ cp server /opt/myserver/
$ touch /opt/myserver/config
3、做成服务
# 以服务启动
$ vim /lib/systemd/system/myserver.service
# 内容
[Unit]
Description=myserver
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=1
WorkingDirectory=/opt/myserver
EnvironmentFile=/opt/myserver/config
ExecStart=/opt/myserver/server
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl start myserver.service
systemctl status myserver.service
systemctl stop myserver.service
systemctl enable/disable myserver.service
systemctl restart myserver.service
systemctl list-units --type=service | grep myserver.service
$ systemctl daemon-reload
$ systemctl start myserver.service
$ systemctl status myserver.service
● myserver.service - myserver
Loaded: loaded (/usr/lib/systemd/system/myserver.service; disabled; vendor preset: disabled)
Active: active (running) since Wed 2023-06-28 22:55:17 EDT; 4s ago
Main PID: 21939 (server)
Tasks: 5
Memory: 740.0K
CGroup: /system.slice/myserver.service
└─21939 /opt/myserver/server
Jun 28 22:55:17 omdev systemd[1]: Started myserver.
$ curl 192.168.43.150:8090/hello
hello world!