Get an io.ByteReader from a net.Conn

The problem is that the underlying net.TCPConn returned by net.Dial as net.Conn only implements the Read(byte[]) (int, err) method. This means that the returned net.Conn satisfies the io.Reader interface, but it does not satisfy the io.ByteReader interface because net.TCPConn doesn't have a ReadByte() (c byte, err error) method.

You can use the bufio.NewReader function to wrap the net.Conn in a type that does implement the io.ByteReader interface.

Example:

package main

import (
    "bufio"
    "encoding/binary"
    "fmt"
    "net"
)

func main() {
    conn, err := net.Dial("tcp", "google.com:80")
    if err != nil {
        panic(err)
    }
    defer conn.Close()

    fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")

    length, err := binary.ReadVarint(bufio.NewReader(conn))
    if err != nil {
    panic(err)
    }
    fmt.Println(length)
}

bufio.Reader implements the ByteReader interface.

Wrapping conn using bufio.NewReader(conn) should work.

Tags:

Go