先上go http 服务代码
package main
import (
"fmt"
"net"
"net/http"
"os"
"strconv"
"time"
)
var (
g_localip string
)
func main() {
var (
port = 8080
host_addr string
err error
)
if len(os.Args) >= 2 {
if port, err = strconv.Atoi(os.Args[1]); err != nil {
fmt.Printf("param2 [%s] must in (1~65535)", os.Args[1])
return
}
}
g_localip = getLocalIP()
host_addr = fmt.Sprintf(":%d", port)
fmt.Printf("%s start httpsvr at [%s]", g_localip, host_addr)
http.HandleFunc("/", mainHandle)
http.ListenAndServe(host_addr, nil)
}
func mainHandle(w http.ResponseWriter, r *http.Request) {
var (
temp string
)
temp = fmt.Sprintf("%s, welcome! \ncurrent service machie is [%s], service time is [%s]",
r.RemoteAddr, g_localip, formatTime())
w.Write([]byte(temp))
}
func formatTime() string {
return fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d.%03d", time.Now().Year(),
time.Now().Month(), time.Now().Day(), time.Now().Hour(), time.Now().Minute(),
time.Now().Second(), time.Now().Nanosecond()/1e6)
}
func getLocalIP() string {
var (
addrs []net.Addr
err error
address net.Addr
ipnet *net.IPNet
ok bool
)
if addrs, err = net.InterfaceAddrs(); err != nil {
return ""
}
for _, address = range addrs {
if ipnet, ok = address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}
将上面的代码编译成http_test并放到/opt/http_test/目录下
进入下面目录
cd /etc/systemd/system/
创建一个名为httptest.service文件,内容填写如下
[Unit]
Description=httptest service
After=network.target
[Service]
Type=simple
ExecStart=/opt/http_test/http_test 8080 &
ExecStop=/bin/kill-s QUIT $MAINPID
User=root
Restart=on-abort
[Install]
WantedBy=multi-user.target
针对刚刚创建的文件添加执行权限
chmod 754 httptest.service
上面节点的含义分别如下
Description服务的简单描述
After依赖,仅当依赖的服务启动之后再启动自定义的服务单元
ExecStart 默认开启8080端口
sudo systemctl daemon-reload
sudo systemctl enable httptest.service
sudo systemctl start httptest.service
--permanent永久生效,没有此参数重启后失效,防火墙打开8080端口,同时刷新防火墙
firewall-cmd --zone=public --add-port=8080/tcp --permanent
firewall-cmd --reload