I'm using Go 1.2 and trying to call TCPConn.SetLinger(0) on a socket that my server is closing due to fatal errors in the input. However, I can't figure out how I would do this. Both net.Listener.Accept() and TCPListener.Accept() return net.Conn, not net.TCPConn. net.Conn does not implement SetLinger. I tried doing a type switch, but then the compiler complains of an "impossible type switch case: conn (type net.Conn) cannot have dynamic type net.TCPConn (missing Close method)". How can net.TCPConn be missing a Close method?? I haven't checked the source, but the documentation lists a close method (and what kind of connection can you not close, anyway?).
It seems like you cannot cast net.Conn to net.TCPConn (because of no Close method), and you can't get a TCPConn on a server, because all the Accept()s return a net.Conn. So how do I actually call SetLinger? (Or for that matter, SetKeepAlive, SetNoDelay?)
After looking more closely, it looks like there is a net.TCPListener.AcceptTCP() which returns a TCPListener, is that really what I have to do? Why can't I get a TCPConn from Accept()? I started it off with net.Listen("tcp", ":4321"), so I know it has to be a TCPConn underneath...
You could use TCPListener.AcceptTCP()
, Accept
just calls AcceptTCP
and returns *TCPConn
as an interface.
From http://golang.org/src/pkg/net/tcpsock_posix.go?s=7727:7771#L233
func (l *TCPListener) Accept() (Conn, error) {
c, err := l.AcceptTCP() //notice this part
if err != nil {
return nil, err
}
return c, nil
}
Or like James mentioned in the comments, you could simply cast it to tcpcon := conn.(*net.TCPConn)
.