在 Go 中创建空闲超时? [英] Creating an idle timeout in Go?

查看:22
本文介绍了在 Go 中创建空闲超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 CloudFlare 用于我的一个高容量网站,它位于我的堆栈前面.

I use CloudFlare for one of my high volume websites, and it sits in front of my stack.

问题是 CloudFlare 除了创建新连接外,还会打开空闲连接,这不是我可以更改的设置.

The thing is CloudFlare leaves idle connections open in addition to creating new ones, and it's not a setting I can change.

当我让 Varnish 或 Nginx 坐在前面监听端口 80 时,它们具有开箱即用的配置来挂断空闲连接.

When I have Varnish or Nginx sitting in front listening on port 80 they have out of the box configuration to hang up the idle connections.

这很好,直到我不得不将用 Go 编写的代理添加到我的堆栈的前面.它使用 net/http 标准库.

This is fine until I had to add a proxy written in Go to the front of my stack. It uses the net/http standard library.

我不是 Go 向导,但根据人们告诉我的内容,只有读写超时设置,而不是挂起空闲连接.

I'm not a Go wizard but based on what people are telling me there are only read and write timeout settings but not hanging up idle connections.

现在我的服务器将充满连接并死掉,除非我设置了一组读写超时,但问题是我的后端有时需要很长时间,这会导致好的请求在不应该被切断时被切断.

Now my server will fill up with connections and die unless I set a set read and write timeouts, but the problem with this is my backend takes a long time sometimes and it's causing good requests to be cut off when they shouldn't.

使用 Go http 处理空闲连接的正确方法是什么?

What is the proper way to handle idle connections with Go http?

编辑 1: 更清楚地说,我使用 httputil.NewSingleHostReverseProxy 来构造一个代理,它公开传输选项,但仅适用于上游.我遇到的问题是下游问题,需要在使用 ReverseProxy 作为处理程序的 http.Server 对象上进行设置.http.Server 不公开传输.

Edit 1: To be more clear, I'm using httputil.NewSingleHostReverseProxy to construct a proxy, which exposes transport options but only for the upstream. The problems I am having are downstream, they need to be set on the http.Server object that uses the ReverseProxy as a handler. http.Server does not expose transport.

编辑 2:我更喜欢空闲超时而不是读取超时,因为后者适用于活动上传者.

Edit 2: I would prefer an idle timeout to a read timeout, since the later would apply to an active uploader.

谢谢

推荐答案

在 Go http 服务器中挂断空闲连接的正确方法是设置 读取超时.

The proper way to hangup idle connections in the Go http server is to set the read timeout.

无需设置写入超时即可挂断空闲客户端.如果它会切断响应,请不要设置或调整此值.

It is not necessary to set the write timeout to hang up on idle clients. Don't set this value or adjust it up if it's cutting off responses.

如果你有长上传,那么使用一个连接状态回调来实现单独的idle和读取超时:

If you have long uploads, then use a connection state callback to implement separate idle and read timeouts:

server.ConnState = func(c net.Conn, cs http.ConnState) {
    switch cs {
    case http.StateIdle, http.StateNew:
        c.SetReadDeadline(time.Now() + idleTimeout)
    case http.StateActive:
        c.SetReadDeadline(time.Now() + activeTimeout)
    }
}

这篇关于在 Go 中创建空闲超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆