4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

io.Copy and timeout

Last updated at Posted at 2015-08-19

io.Copy is useful in passing date from Reader to Writer. However, io.Copy hides Read(), Write() method calls.

When we want to set timeout to TCP socket I/O, I found wrapping this with customized type is the straight forward way like this:

package main

import (
	"io"
	"log"
	"net"
	"syscall"
	"time"
)

type IdleTimeoutConn struct {
	Conn net.Conn
}

func (self IdleTimeoutConn) Read(buf []byte) (int, error) {
	self.Conn.SetDeadline(time.Now().Add(5 * time.Second))
	return self.Conn.Read(buf)
}

func (self IdleTimeoutConn) Write(buf []byte) (int, error) {
	self.Conn.SetDeadline(time.Now().Add(5 * time.Second))
	return self.Conn.Write(buf)
}

func main() {
	ln, err := net.Listen("tcp", ":7")
	if err != nil {
		panic(err)
	}
	for {
		con, err := ln.Accept()
		if err != nil {
			if eno, ok := err.(syscall.Errno); ok && eno.Temporary() {
				continue
			}
			panic(err)
		}
		go func() {
			tcon := IdleTimeoutConn{
				Conn: con,
			}
			log.Print(io.Copy(tcon, tcon))
		}()
	}
}
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?