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))
}()
}
}