如何让 Go 的 http.Server 闲置一段时间后退出?

How can I make Go's http.Server exit after being idle for a period of time?

我正在使用使用 systemd 套接字激活的标准库 net/http 包在 Go 中编写 Web 服务器。

我有基本的工作原理,这样服务器在第一次与监听套接字建立连接时启动,并且我可以在收到信号时正常关闭(即 systemctl stop 将在不中断的情况下工作活跃请求)。

我希望服务器在闲置一段时间后自动退出。类似于以下内容:

  1. 当最后一个活动请求完成时,启动一个计时器,比如 30 秒。
  2. 如果在此期间有任何新请求到达,则停止计时器。
  3. 如果定时器超时,执行正常关机。

我们的想法是释放服务器正在使用的资源,因为我们知道 systemd 会在新客户端出现时再次启动我们。

第 (1) 和 (2) 部分我不确定。理想情况下,我想要一个不涉及修改所有已注册处理程序的解决方案。

使用@CeriseLimón 的建议,以下帮助程序类型似乎可以解决问题:

type IdleTracker struct {
    mu     sync.Mutex
    active map[net.Conn]bool
    idle   time.Duration
    timer  *time.Timer
}

func NewIdleTracker(idle time.Duration) *IdleTracker {
    return &IdleTracker{
        active: make(map[net.Conn]bool),
        idle:   idle,
        timer:  time.NewTimer(idle),
    }
}

func (t *IdleTracker) ConnState(conn net.Conn, state http.ConnState) {
    t.mu.Lock()
    defer t.mu.Unlock()

    oldActive := len(t.active)
    switch state {
    case http.StateNew, http.StateActive, http.StateHijacked:
        t.active[conn] = true
        // stop the timer if we transitioned to idle
        if oldActive == 0 {
            t.timer.Stop()
        }
    case http.StateIdle, http.StateClosed:
        delete(t.active, conn)
        // Restart the timer if we've become idle
        if oldActive > 0 && len(t.active) == 0 {
            t.timer.Reset(t.idle)
        }
    }
}

func (t *IdleTracker) Done() <-chan time.Time {
    return t.timer.C
}

将其 ConnState 方法分配给服务器的 ConnState 成员将跟踪服务器是否忙碌,并在我们空闲达到请求的时间量时向我们发出信号:

idle := NewIdleTracker(5 * time.Second)
server.ConnState = idle.ConnState

go func() {
    <-idle.Done()
    if err := server.Shutdown(context.Background()); err != nil {
        log.Fatalf("error shutting down: %v\n", err)
    }
}()