标签 Kernel 下的文章

Go官方 HTTP/3 实现终迎曙光:x/net/http3 提案启动,QUIC 基础已就位

本文永久链接 – https://tonybai.com/2025/08/02/proposal-http3

大家好,我是Tony Bai。

在社区长达数年的热切期盼之后,Go 官方终于迈出了支持 HTTP/3 的关键一步。一项编号为#70914的新提案,正式建议在 x/net/http3 中添加一个实验性的 HTTP/3 实现。这一进展建立在另一项更基础的提案 #58547(x/net/quic) 之上,该提案的实现已取得重大进展,并已从内部包移至公开的 x/net/quic。这意味着 Go 的网络栈即将迎来一次基于 UDP 的、彻底的现代化升级。本文将带您回顾 Go 社区对 HTTP/3 的漫长期待,深入解读官方 QUIC 和 HTTP/3 的实现策略,并探讨其对未来 Go 网络编程的深远影响。

一场长达五年的等待

对 HTTP/3 的支持,可以说是 Go 社区近年来呼声最高的功能之一。早在 2019 年,issue #32204 就被创建,用于追踪在标准库中支持 HTTP/3 的进展。在随后的五年里,随着 Chrome、Firefox 等主流浏览器以及 Cloudflare 等基础设施提供商纷纷拥抱 HTTP/3,社区的期待也日益高涨。

在此期间,由 Marten Seemann 维护的第三方库 quic-go 成为了 Go 生态中事实上的标准,为 Caddy 等项目提供了生产级的 QUIC 和 HTTP/3 支持。然而,许多开发者仍然期盼一个“电池内置”的官方解决方案,以保证与 Go 标准库(特别是 net/http 和 crypto/tls)的最佳集成和长期维护。

Go 团队对此一直持谨慎态度,主要原因在于:

  1. 协议稳定性:在 QUIC 和 HTTP/3 的 IETF 标准(RFC 9000 和 RFC 9114)正式发布前,过早投入实现可能会面临巨大的变更成本。
  2. API 设计复杂性:QUIC 协议引入了连接、流、0-RTT 等新概念,其 API 设计需要与现有的 net.Conn 和 net.Listener 体系进行权衡,这是一个巨大的挑战。
  3. 实现难度巨大:一个高性能、安全的 QUIC 协议栈,涉及复杂的流量控制、拥塞控制、丢包恢复等机制,其实现工作量远超 HTTP/2。

两步走战略:先 QUIC,后 HTTP/3

现在,随着协议的标准化和 crypto/tls 中 QUIC 支持的落地,Go 团队终于启动了官方的实现计划,并采取了清晰的“两步走”战略。

第一步:构建 QUIC 基础 (x/net/quic)

提案 #58547 旨在 golang.org/x/net/quic 中提供一个 QUIC 协议的实现。这是支持 HTTP/3 的必要前提。经过一段时间的开发,该包的实现已取得重大进展。

Go 团队的核心成员 neild 最近宣布,该 QUIC 实现已从内部包 (internal/quic) 移至公开的 x/net/quic,虽然仍处于实验阶段且 API 可能变化,但这标志着它已足够成熟,可以供社区“尝鲜”和提供反馈。

x/net/quic 的核心 API 概念:

  • Endpoint (原 Listener): 在一个网络地址上监听 QUIC 流量。
  • Conn: 代表一个客户端和服务器之间的 QUIC 连接,可以承载多个流。
  • Stream: 一个有序、可靠的字节流,类似于一个 TCP 连接。
// 客户端发起连接
conn, err := quic.Dial(ctx, "udp", "127.0.0.1:8000", &quic.Config{})

// 服务器接受连接
endpoint, err := quic.Listen("udp", "127.0.0.1:8000", &quic.Config{})
conn, err := endpoint.Accept(ctx)

// 在连接上创建和接受流
stream, err := conn.NewStream(ctx)
stream, err := conn.AcceptStream(ctx)

// 对流进行读写操作
n, err = stream.Read(buf)
n, err = stream.Write(buf)
stream.Close()

值得注意的是,官方实现并未直接采用 quic-go 的代码,rsc 在讨论中解释了原因,包括 API 设计理念的差异、代码风格、测试框架依赖以及从零开始实现可能更易于维护等。

第二步:实现 HTTP/3 (x/net/http3)

在 x/net/quic 的基础上,提案 #70914 正式启动了 x/net/http3 的开发。与 QUIC 一样,它将首先在内部包 (x/net/internal/http3) 中进行开发,待 API 稳定后再移至公开包,并提交最终的 API 审查提案。

从 gopherbot 自动发布的 CL(代码变更)列表中,我们可以看到 HTTP/3 的实现正在紧锣密鼓地进行中,涵盖了 QPACK(HTTP/3 的头部压缩算法)、Transport、Server、请求/响应体传输等核心组件。

对 Go 网络编程的深远影响

官方 QUIC 和 HTTP/3 的到来,将为 Go 开发者带来革命性的变化:

  1. 透明的协议升级:可以预见,未来的 net/http 包将能够像当年无缝支持 HTTP/2 一样,透明地支持 HTTP/3。开发者可能无需修改现有代码,http.Get(“https://example.com/”) 就可能自动通过 UDP 下的 QUIC 协议执行,正如 ianlancetaylor 在讨论中确认的那样。

  2. 解决队头阻塞 (Head-of-Line Blocking):HTTP/3 最大的优势之一是解决了 TCP 队头阻塞问题。对于需要处理大量并发请求的 Go 微服务,这意味着更低的延迟和更高的吞吐量,尤其是在网络不稳定的情况下。

  3. 更快的连接建立:QUIC 支持 0-RTT 连接建立,对于需要频繁建立新连接的应用场景,可以显著降低握手延迟。

  4. 原生多路复用传输层:QUIC 本身就是一个多路复用的传输协议。虽然提案的初期重点是支持 HTTP/3,但一个标准化的 QUIC API 将为 gRPC over QUIC、WebTransport 以及其他需要多流、低延迟通信的自定义协议打开大门。

终极形态——当 QUIC 走进 Linux 内核

尽管 x/net/quic 的开发标志着 Go 官方在用户空间迈出了重要一步,但关于 QUIC 协议的终极愿景,则指向了更深的层次:Linux 内核原生支持。最近,由 Xin Long 提交的一系列补丁,首次将内核态 QUIC 的实现提上了 mainline 的议程

为什么要将 QUIC 移入内核?

将 QUIC 从用户空间库(如 x/net/quic 或 quic-go)下沉到内核,主要有以下几个核心动机:

  1. 极致的性能潜力:内核实现能够充分利用现代网络硬件的协议卸载(protocol offload)能力,例如 GSO/GRO (Generic Segmentation/Receive Offload)。这将极大地降低 CPU 在处理大量小型 UDP 包时的开销,释放出用户空间实现难以企及的性能潜力。
  2. 更广泛的可用性:一旦 QUIC 成为内核支持的协议(如 IPPROTO_QUIC),任何应用程序都可以像使用 TCP 或 UDP 一样,通过标准的 socket() 系统调用来使用它,而无需绑定到任何特定的用户空间库。
  3. 统一的生态系统:内核级别的支持将极大地促进生态系统的发展。Samba、NFS 甚至 curl 等项目已经表现出对内核态 QUIC 的浓厚兴趣。对于 Go 开发者而言,这意味着未来不仅是 net/http,甚至标准库的其他部分或底层系统调用,都可能从 QUIC 中受益。

当前的实现与挑战

Xin Long 的补丁集展示了一个高度集成化的设计:

  • 熟悉的 Sockets API:开发者将能够使用 socket(AF_INET, SOCK_STREAM, IPPROTO_QUIC) 这样的调用来创建一个 QUIC 套接字,并继续使用 bind(), connect(), listen(), accept() 等熟悉的 API。
  • 用户空间 TLS 握手:与内核 TLS (KTLS) 的设计类似,复杂的 TLS 握手和证书验证逻辑仍然被委托给用户空间处理。一旦握手完成,内核将接管加密和解密的数据流。
  • 性能仍在优化:初步的基准测试显示,当前的内核实现性能尚不及 KTLS 甚至原生 TCP。这主要是由于缺少硬件卸载支持、额外的内存拷贝以及 QUIC 头部加密的开销。但随着实现的成熟和硬件厂商的跟进,这一差距有望迅速缩小。

不过,预计内核态 QUIC 的合入可能要到 2026 年甚至更晚。

小结:Go 网络生态的下一座里程碑

尽管距离在 Go 标准库中稳定地使用 http.Server{…}.ListenAndServeQUIC() 可能还有一段时间,但 x/net/quic 的公开和 x/net/http3 提案的启动,标志着 Go 官方已经吹响了向下一代网络协议进军的号角。

对于 Go 社区而言,这是一个令人振奋的信号。它不仅回应了开发者们长久以来的期待,也确保了 Go 在未来依然是构建高性能、现代化网络服务的首选语言。我们期待着 x/net/http3 的成熟,并最终看到它被无缝地集成到 net/http 标准库中,为所有 Go 开发者带来更快、更可靠的网络体验。

参考资料

  • https://github.com/golang/go/issues/70914
  • https://github.com/golang/go/issues/58547
  • https://github.com/golang/go/issues/32204
  • https://lwn.net/Articles/1029851/

你的Go技能,是否也卡在了“熟练”到“精通”的瓶颈期?

  • 想写出更地道、更健壮的Go代码,却总在细节上踩坑?
  • 渴望提升软件设计能力,驾驭复杂Go项目却缺乏章法?
  • 想打造生产级的Go服务,却在工程化实践中屡屡受挫?

继《Go语言第一课》后,我的《Go语言进阶课》终于在极客时间与大家见面了!

我的全新极客时间专栏 《Tony Bai·Go语言进阶课》就是为这样的你量身打造!30+讲硬核内容,带你夯实语法认知,提升设计思维,锻造工程实践能力,更有实战项目串讲。

目标只有一个:助你完成从“Go熟练工”到“Go专家”的蜕变! 现在就加入,让你的Go技能再上一个新台阶!


商务合作方式:撰稿、出书、培训、在线课程、合伙创业、咨询、广告合作。如有需求,请扫描下方公众号二维码,与我私信联系。

如何像gitlab-runner那样将Go应用安装为系统服务

本文永久链接 – https://tonybai.com/2022/09/12/how-to-install-a-go-app-as-a-system-service-like-gitlab-runner

《让reviewdog支持gitlab-push-commit,守住代码质量下限》一文中,gitlab-runner(一个Go语言开发的应用)通过自身提供的install命令将自己安装为了一个系统服务(如下面步骤):

# Create a GitLab CI user
sudo useradd --comment 'GitLab Runner' --create-home gitlab-runner --shell /bin/bash

# Install and run as service
sudo gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner
sudo gitlab-runner start

在主流新版linux上(其他os或linux上的旧版守护服务管理器如sysvinit、upstart等,我们暂不care),系统服务就是由systemd管理的daemon process(守护进程)。

systemd是什么?linux主机上电后,os内核被加载并启动,os内核完成初始化以后,由内核第一个启动的程序是init程序,其PID(进程ID)为1,它为系统里所有进程的“祖先”,systemd便是主流新版linux中的那个init程序,它负责在主机启动后拉起所有安装为系统服务的程序

这些被systemd拉起的服务程序以守护进程(daemon process)的形式运行,那什么又是守护进程呢?《UNIX环境高级编程3rd(Advanced Programming in the UNIX Environment)》一书中是这样定义的:

Daemons are processes that live for a long time. They are often started when the system is bootstrapped and terminate only when the system is shut down. Because they don’t have a controlling terminal, we say that they run in the background. UNIX systems have numerous daemons that perform day-to-day activities.

守护进程是长期存在的进程。它们通常在系统启动时被启动,并在系统关闭时才终止。因为它们没有控制终端,我们说它们是在后台运行的。UNIX系统有许多执行日常活动的守护进程。

该书还提供了一个用户层应用程序将自己变为守护进程的标准步骤(编码规则(coding rules)),并给出了一个C语言示例:

#include "apue.h"
#include <syslog.h>
#include <fcntl.h>
#include <sys/resource.h>

void
daemonize(const char *cmd)
{
    int i, fd0, fd1, fd2;
    pid_t pid;
    struct rlimit rl;
    struct sigaction sa;

    /*
     * Clear file creation mask.
     */
    umask(0);
    /*
     * Get maximum number of file descriptors.
     */
    if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
        err_quit("%s: can’t get file limit", cmd);
    /*
     * Become a session leader to lose controlling TTY.
     */
    if ((pid = fork()) < 0)
        err_quit("%s: can’t fork", cmd);
    else if (pid != 0) /* parent */
        exit(0);
    setsid();

    /*
     * Ensure future opens won’t allocate controlling TTYs.
     */
    sa.sa_handler = SIG_IGN;
    sigemptyset(&sa.sa_mask);

    sa.sa_flags = 0;
    if (sigaction(SIGHUP, &sa, NULL) < 0)
        err_quit("%s: can’t ignore SIGHUP", cmd);
    if ((pid = fork()) < 0)
        err_quit("%s: can’t fork", cmd);
    else if (pid != 0) /* parent */
        exit(0);
    /*
     * Change the current working directory to the root so
     * we won’t prevent file systems from being unmounted.
     */
    if (chdir("/") < 0)
        err_quit("%s: can’t change directory to /", cmd);
    /*
     * Close all open file descriptors.
     */
    if (rl.rlim_max == RLIM_INFINITY)
        rl.rlim_max = 1024;
    for (i = 0; i < rl.rlim_max; i++)
        close(i);
    /*
     * Attach file descriptors 0, 1, and 2 to /dev/null.
     */
    fd0 = open("/dev/null", O_RDWR);
    fd1 = dup(0);
    fd2 = dup(0);
    /*
     * Initialize the log file.
     */
    openlog(cmd, LOG_CONS, LOG_DAEMON);
    if (fd0 != 0 || fd1 != 1 || fd2 != 2) {
        syslog(LOG_ERR, "unexpected file descriptors %d %d %d",
          fd0, fd1, fd2);
        exit(1);
    }
}

那么,Go应用程序是否可以参考上面的转换步骤将自己转换为一个守护进程呢?很遗憾!Go团队说很难做到。Go社区倒是有很多第三方的方案,比如像go-daemon这样的第三方实现,不过我并没有验证过这些方案,不保证完全ok。

Go团队推荐通过像systemd这样的init system来实现Go程序的守护进程转换。gitlab-runner就是将自己安装为system服务,并由systemd对其进行管理的。

题外话:其实,自从有了容器技术(比如:docker)后,daemon service(守护进程服务)的需求似乎减少了。因为使用-d选项运行容器,应用本身就运行于后台,使用–restart=always/on-failure选项,容器引擎(比如docker engine)会帮我们管理service,并在service宕掉后重启service。

那么,我们如何像gitlab-runner那样将自己安装为一个systemd service呢?我们继续向下看。

注意:这里只是将Go应用安装成一个systemd service,并不是自己将自己转换为守护进程,安装为systemd service本身是可行的,也是安全的。

翻看gitlab-runner源码,你会发现gitlab-runner将自己安装为系统服务全依仗于github.com/kardianos/service这个Go包,这个包是Go标准库database包维护者之一Daniel Theophanes开源的系统服务操作包,该包屏蔽了os层的差异,为开发人员提供了相对简单的Service操作接口,包括下面这些控制动作:

// github.com/kardianos/service/blob/master/service.go
var ControlAction = [5]string{"start", "stop", "restart", "install", "uninstall"}

好了,下面我们就用一个例子myapp来介绍一下如何利用kardianos/service包让你的Go应用具备将自己安装为system service的能力

myapp是一个http server,它在某个端口上提供服务,当收到请求时,返回”Welcome”字样的应答:

// https://github.com/bigwhite/experiments/blob/master/system-service/main.go

func run(config string) error {
    ... ...

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Printf("[%s]: receive a request from: %s\n", c.Server.Addr, r.RemoteAddr)
        w.Write([]byte("Welcome"))
    })
    fmt.Printf("listen on %s\n", c.Server.Addr)
    return http.ListenAndServe(c.Server.Addr, nil)
}

现在我们要为myapp增加一些能力,让它支持将自己安装为systemd service,并可以通过subcommand启动(start)、停止(stop)和卸载(uninstall)systemd service。

我们首先通过os包和flag包为该程序增加subcommand和其参数的解析能力。我们不使用第三方命令行参数解析包,只是用标准库的flag包。由于myapp支持subcommand,我们需要为每个带命令行参数的subcommand单独申请一个FlagSet实例,如下面代码中的installCommand和runCommand。每个subcommand的命令行参数也要绑定到各自subcommand对应的FlagSet实例上,比如下面代码init函数体中的内容。

另外由于使用了subcommand,默认的flag.Usage不再能满足我们的要求了,我们需要自己实现一个usage函数并赋值给flag.Usage:

// https://github.com/bigwhite/experiments/blob/master/system-service/main.go

var (
    installCommand = flag.NewFlagSet("install", flag.ExitOnError)
    runCommand     = flag.NewFlagSet("run", flag.ExitOnError)
    user           string
    workingdir     string
    config         string
)

const (
    defaultConfig = "/etc/myapp/config.ini"
)

func usage() {
    s := `
USAGE:
   myapp command [command options] 

COMMANDS:
     install               install service
     uninstall             uninstall service
     start                 start service
     stop                  stop service
     run                   run service

OPTIONS:
     -config string
        config file of the service (default "/etc/myapp/config.ini")
     -user string
        user account to run the service
     -workingdir string
        working directory of the service`

    fmt.Println(s)
}

func init() {
    installCommand.StringVar(&user, "user", "", "user account to run the service")
    installCommand.StringVar(&workingdir, "workingdir", "", "working directory of the service")
    installCommand.StringVar(&config, "config", "/etc/myapp/config.ini", "config file of the service")
    runCommand.StringVar(&config, "config", defaultConfig, "config file of the service")
    flag.Usage = usage
}

func main() {
    var err error
    n := len(os.Args)
    if n <= 1 {
        fmt.Printf("invalid args\n")
        flag.Usage()
        return
    }

    subCmd := os.Args[1] // the second arg

    // get Config
    c, err := getServiceConfig(subCmd)
    if err != nil {
        fmt.Printf("get service config error: %s\n", err)
        return
    }
... ...
}

这些都完成后,我们在getServiceConfig函数中获取即将安装为systemd service的本服务的元配置信息:

// https://github.com/bigwhite/experiments/blob/master/system-service/config.go

func getServiceConfig(subCmd string) (*service.Config, error) {
    c := service.Config{
        Name:             "myApp",
        DisplayName:      "Go Daemon Service Demo",
        Description:      "This is a Go daemon service demo",
        Executable:       "/usr/local/bin/myapp",
        Dependencies:     []string{"After=network.target syslog.target"},
        WorkingDirectory: "",
        Option: service.KeyValue{
            "Restart": "always", // Restart=always
        },
    }   

    switch subCmd {
    case "install":
        installCommand.Parse(os.Args[2:])
        if user == "" {
            fmt.Printf("error: user should be provided when install service\n")
            return nil, errors.New("invalid user")
        }
        if workingdir == "" {
            fmt.Printf("error: workingdir should be provided when install service\n")
            return nil, errors.New("invalid workingdir")
        }
        c.UserName = user
        c.WorkingDirectory = workingdir

        // arguments
        // ExecStart=/usr/local/bin/myapp "run" "-config" "/etc/myapp/config.ini"
        c.Arguments = append(c.Arguments, "run", "-config", config)
    case "run":
        runCommand.Parse(os.Args[2:]) // parse config
    }   

    return &c, nil
}

这里要注意的是service.Config中的Option和Arguments,前者用于在systemd service unit配置文件中放置任意的键值对(比如这里的Restart=always),而Arguments则会被组成为ExecStart键的值,该值会在start service时传入使用。

接下来,我们便利用service包基于加载的Config创建操作服务的实例(srv),然后将它和subCommand一并传入runServiceControl实现对systemd service的控制(如下面代码)。

// https://github.com/bigwhite/experiments/blob/master/system-service/main.go
func main() {

    // ... ...
    c, err := getServiceConfig(subCmd)
    if err != nil {
        fmt.Printf("get service config error: %s\n", err)
        return
    }

    prg := &NullService{}
    srv, err := service.New(prg, c)
    if err != nil {
        fmt.Printf("new service error: %s\n", err)
        return
    }

    err = runServiceControl(srv, subCmd)
    if err != nil {
        fmt.Printf("%s operation error: %s\n", subCmd, err)
        return
    }

    fmt.Printf("%s operation ok\n", subCmd)
    return
}

func runServiceControl(srv service.Service, subCmd string) error {
    switch subCmd {
    case "run":
        return run(config)
    default:
        return service.Control(srv, subCmd)
    }
}

好了,代码已经完成!现在让我们来验证一下myapp的能力。

我们先来完成编译和二进制程序的安装:

$make
go build -o myapp main.go config.go

$sudo make install
cp ./myapp /usr/local/bin
$sudo make install-cfg
mkdir -p /etc/myapp
cp ./config.ini /etc/myapp

接下来,我们就来将myapp安装为systemd的服务:

$sudo ./myapp install -user tonybai -workingdir /home/tonybai
install operation ok

$sudo systemctl status myApp
● myApp.service - This is a Go daemon service demo
     Loaded: loaded (/etc/systemd/system/myApp.service; enabled; vendor preset: enabled)
     Active: inactive (dead)

我们看到安装后,myApp已经成为了myApp.service,并处于inactive状态,其systemd unit文件/etc/systemd/system/myApp.service内容如下:

$sudo cat /etc/systemd/system/myApp.service
[Unit]
Description=This is a Go daemon service demo
ConditionFileIsExecutable=/usr/local/bin/myapp

After=network.target syslog.target 

[Service]
StartLimitInterval=5
StartLimitBurst=10
ExecStart=/usr/local/bin/myapp "run" "-config" "/etc/myapp/config.ini"

WorkingDirectory=/home/tonybai
User=tonybai

Restart=always

RestartSec=120
EnvironmentFile=-/etc/sysconfig/myApp

[Install]
WantedBy=multi-user.target

接下来,我们来启动一下该服务:

$sudo ./myapp start
start operation ok

$sudo systemctl status myApp
● myApp.service - This is a Go daemon service demo
     Loaded: loaded (/etc/systemd/system/myApp.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2022-09-09 23:30:01 CST; 5s ago
   Main PID: 623859 (myapp)
      Tasks: 6 (limit: 12651)
     Memory: 1.3M
     CGroup: /system.slice/myApp.service
             └─623859 /usr/local/bin/myapp run -config /etc/myapp/config.ini

Sep 09 23:30:01 tonybai systemd[1]: Started This is a Go daemon service demo.
Sep 09 23:30:01 tonybai myapp[623859]: listen on :65432

我们看到myApp服务成功启动,并在65432这个端口上监听!

我们利用curl向这个端口发送一个请求:

$curl localhost:65432
Welcome                                                                         

$sudo systemctl status myApp
● myApp.service - This is a Go daemon service demo
     Loaded: loaded (/etc/systemd/system/myApp.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2022-09-09 23:30:01 CST; 1min 27s ago
   Main PID: 623859 (myapp)
      Tasks: 6 (limit: 12651)
     Memory: 1.4M
     CGroup: /system.slice/myApp.service
             └─623859 /usr/local/bin/myapp run -config /etc/myapp/config.ini

Sep 09 23:30:01 tonybai systemd[1]: Started This is a Go daemon service demo.
Sep 09 23:30:01 tonybai myapp[623859]: listen on :65432
Sep 09 23:31:24 tonybai myapp[623859]: [:65432]: receive a request from: 127.0.0.1:10348

我们看到myApp服务运行正常并返回预期应答结果。

现在我们利用stop subcommand停掉该服务:

$sudo systemctl status myApp
● myApp.service - This is a Go daemon service demo
     Loaded: loaded (/etc/systemd/system/myApp.service; enabled; vendor preset: enabled)
     Active: inactive (dead) since Fri 2022-09-09 23:33:03 CST; 3s ago
    Process: 623859 ExecStart=/usr/local/bin/myapp run -config /etc/myapp/config.ini (code=killed, signal=TERM)
   Main PID: 623859 (code=killed, signal=TERM)

Sep 09 23:30:01 tonybai systemd[1]: Started This is a Go daemon service demo.
Sep 09 23:30:01 tonybai myapp[623859]: listen on :65432
Sep 09 23:31:24 tonybai myapp[623859]: [:65432]: receive a request from: 127.0.0.1:10348
Sep 09 23:33:03 tonybai systemd[1]: Stopping This is a Go daemon service demo...
Sep 09 23:33:03 tonybai systemd[1]: myApp.service: Succeeded.
Sep 09 23:33:03 tonybai systemd[1]: Stopped This is a Go daemon service demo.

修改配置/etc/myapp/config.ini(将监听端口从65432改为65431),然后再重启该服务:

$sudo cat /etc/myapp/config.ini
[server]
addr=":65431"

$sudo ./myapp start
start operation ok

$sudo systemctl status myApp
● myApp.service - This is a Go daemon service demo
     Loaded: loaded (/etc/systemd/system/myApp.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2022-09-09 23:34:38 CST; 3s ago
   Main PID: 624046 (myapp)
      Tasks: 6 (limit: 12651)
     Memory: 1.4M
     CGroup: /system.slice/myApp.service
             └─624046 /usr/local/bin/myapp run -config /etc/myapp/config.ini

Sep 09 23:34:38 tonybai systemd[1]: Started This is a Go daemon service demo.
Sep 09 23:34:38 tonybai myapp[624046]: listen on :65431

从systemd的状态日志中我们看到myApp服务启动成功,并改为监听65431端口,我们访问一下该端口:

$curl localhost:65431
Welcome                                                                                                                      

$curl localhost:65432
curl: (7) Failed to connect to localhost port 65432: Connection refused

从上述结果可以看出,我们的配置更新和重启都是成功的!

我们亦可以使用myapp的uninstall功能从systemd中卸载该服务:

$sudo ./myapp uninstall
uninstall operation ok
$sudo systemctl status myApp
Unit myApp.service could not be found.

好了,到这里我们看到:在文章开始处提出的给Go应用增加将自己安装为systemd service的能力的目标已经顺利实现了。

最后小结一下:service包让我们的程序有了将自己安装为system service的能力。它也可以让你开发出将其他程序安装为一个system service的能力,不过这个作业就留给大家了:)。大家如有问题,欢迎在评论区留言。

本文涉及的代码可以在这里下载。


“Gopher部落”知识星球旨在打造一个精品Go学习和进阶社群!高品质首发Go技术文章,“三天”首发阅读权,每年两期Go语言发展现状分析,每天提前1小时阅读到新鲜的Gopher日报,网课、技术专栏、图书内容前瞻,六小时内必答保证等满足你关于Go语言生态的所有需求!2022年,Gopher部落全面改版,将持续分享Go语言与Go应用领域的知识、技巧与实践,并增加诸多互动形式。欢迎大家加入!

img{512x368}
img{512x368}

img{512x368}
img{512x368}

我爱发短信:企业级短信平台定制开发专家 https://tonybai.com/。smspush : 可部署在企业内部的定制化短信平台,三网覆盖,不惧大并发接入,可定制扩展; 短信内容你来定,不再受约束, 接口丰富,支持长短信,签名可选。2020年4月8日,中国三大电信运营商联合发布《5G消息白皮书》,51短信平台也会全新升级到“51商用消息平台”,全面支持5G RCS消息。

著名云主机服务厂商DigitalOcean发布最新的主机计划,入门级Droplet配置升级为:1 core CPU、1G内存、25G高速SSD,价格5$/月。有使用DigitalOcean需求的朋友,可以打开这个链接地址:https://m.do.co/c/bff6eed92687 开启你的DO主机之路。

Gopher Daily(Gopher每日新闻)归档仓库 – https://github.com/bigwhite/gopherdaily

我的联系方式:

  • 微博:https://weibo.com/bigwhite20xx
  • 博客:tonybai.com
  • github: https://github.com/bigwhite

商务合作方式:撰稿、出书、培训、在线课程、合伙创业、咨询、广告合作。

如发现本站页面被黑,比如:挂载广告、挖矿等恶意代码,请朋友们及时联系我。十分感谢! Go语言第一课 Go语言进阶课 AI原生开发工作流实战 Go语言精进之路1 Go语言精进之路2 Go语言第一课 Go语言编程指南
商务合作请联系bigwhite.cn AT aliyun.com
这里是 Tony Bai的个人Blog,欢迎访问、订阅和留言! 订阅Feed请点击上面图片

如果您觉得这里的文章对您有帮助,请扫描上方二维码进行捐赠 ,加油后的Tony Bai将会为您呈现更多精彩的文章,谢谢!

如果您希望通过微信捐赠,请用微信客户端扫描下方赞赏码:

如果您希望通过比特币或以太币捐赠,可以扫描下方二维码:

比特币:

以太币:

如果您喜欢通过微信浏览本站内容,可以扫描下方二维码,订阅本站官方微信订阅号“iamtonybai”;点击二维码,可直达本人官方微博主页^_^:
本站Powered by Digital Ocean VPS。
选择Digital Ocean VPS主机,即可获得10美元现金充值,可 免费使用两个月哟! 著名主机提供商Linode 10$优惠码:linode10,在 这里注册即可免费获 得。阿里云推荐码: 1WFZ0V立享9折!


View Tony Bai's profile on LinkedIn
DigitalOcean Referral Badge

文章

评论

  • 正在加载...

分类

标签

归档



View My Stats