Read whole data with Golang net.Conn.Read

It highly depends on what you’re trying to do, and what kind of data you’re expecting, for example if you just want to read until the EOF you could use something like this:

func main() {
    conn, err := net.Dial("tcp", "google.com:80")
    if err != nil {
        fmt.Println("dial error:", err)
        return
    }
    defer conn.Close()
    fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")

    buf := make([]byte, 0, 4096) // big buffer
    tmp := make([]byte, 256)     // using small tmo buffer for demonstrating
    for {
        n, err := conn.Read(tmp)
        if err != nil {
            if err != io.EOF {
                fmt.Println("read error:", err)
            }
            break
        }
        //fmt.Println("got", n, "bytes.")
        buf = append(buf, tmp[:n]...)

    }
    fmt.Println("total size:", len(buf))
    //fmt.Println(string(buf))
}

//edit: for completeness sake and @fabrizioM’s great suggestion, which completely skipped my mind:

func main() {
    conn, err := net.Dial("tcp", "google.com:80")
    if err != nil {
        fmt.Println("dial error:", err)
        return
    }
    defer conn.Close()
    fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
    var buf bytes.Buffer
    io.Copy(&buf, conn)
    fmt.Println("total size:", buf.Len())
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)