HTTP客户端,空闲超时

huangapple go评论76阅读模式
英文:

HTTP client, idle timeout

问题

如何在Go的HTTP客户端中设置空闲超时时间?

空闲超时时间指的是在HTTP客户端内部调用Conn接口的Read/Write方法时的超时时间。当客户端下载文件时,如果达到了读取超时时间,可能会导致下载失败,因此设置空闲超时时间是很有用的。

英文:

How to make idle timeout in Go HTTP client?

Idle timeout means timeout on calling Read/Write methods of Conn interface from HTTP client internals. It can be useful when client downloads file and in some moment downloading fails because read timeout reached.

答案1

得分: 1

你需要创建自己的net.Dialer,它返回一个设置了适当的读写超时的net.Conn

Conn的结构大致如下:

// Conn包装了net.Conn,并为每个读写操作设置了截止时间。
type Conn struct {
	net.Conn
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

func (c *Conn) Read(b []byte) (int, error) {
	err := c.Conn.SetReadDeadline(time.Now().Add(c.ReadTimeout))
	if err != nil {
		return 0, err
	}
	return c.Conn.Read(b)
}

func (c *Conn) Write(b []byte) (int, error) {
	err := c.Conn.SetWriteDeadline(time.Now().Add(c.WriteTimeout))
	if err != nil {
		return 0, err
	}
	return c.Conn.Write(b)
}

这样,你就可以使用自定义的Conn类型来设置读写操作的截止时间了。

英文:

You need to create your own net.Dialer, that returns a net.Conn which sets the appropriate read and write deadlines.

The Conn would look something like this:

// Conn wraps a net.Conn, and sets a deadline for every read
// and write operation.
type Conn struct {
	net.Conn
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}
 
func (c *Conn) Read(b []byte) (int, error) {
	err := c.Conn.SetReadDeadline(time.Now().Add(c.ReadTimeout))
	if err != nil {
		return 0, err
	}
	return c.Conn.Read(b)
}
 
func (c *Conn) Write(b []byte) (int, error) {
	err := c.Conn.SetWriteDeadline(time.Now().Add(c.WriteTimeout))
	if err != nil {
		return 0, err
	}
	return c.Conn.Write(b)
}

huangapple
  • 本文由 发表于 2015年1月6日 01:14:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/27784521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定