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

查看:203
本文介绍了在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.

这是很好的,直到我不得不添加一个代码写在我的堆栈前面。它使用 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:

感谢

推荐答案

在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.

如果您有长时间上传的内容,请使用连接状态回调以实现单独的空闲和读取超时:

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天全站免登陆