How to populate net.Buffers in Go

Viewed 346

I am trying to use net.Buffers as follows, to read a string into it:

package main

import (
    "fmt"
    "net"
)

func main() {
    msg := "Hello"
    var bufs net.Buffers
    n, err := bufs.Read([]byte(msg))
    if err != nil {
        fmt.Println("bufs.Read error:", err)
        return
    }
    fmt.Printf("Read %d bytes", n)
}

However, when run bufs.Read(...) fails with:

bufs.Read error: EOF

Contrary to what I thought bufs.Read(...) is NOT reading the input argument of this API into itself.

So, how can I fill bufs with some data, that can be written to something like a net.Conn ?

1 Answers

net.Buffers.Read() is to implement io.Reader. Please read the doc what Read() means and how it should work.

In short, the Read() method is used to read data into the slice you pass to it, data read will be written to that slice.

To read from a net.Buffers, first "place" some data into it. net.Buffers is a slice of slices:

type Buffers [][]byte

So simply use the builtin append() function to append slices to it:

var bufs net.Buffers
bufs = append(bufs, []byte("Hello"))
bufs = append(bufs, []byte(" World"))

And to read from it:

data := make([]byte, 100)
n, err := bufs.Read(data)
if err != nil {
    if err == io.EOF {
        // This just means everything from bufs was read,
        // and data isn't filled completely
    } else {
        fmt.Println("bufs.Read error:", err)
        return
    }
}
fmt.Printf("Read %d bytes\n", n)
fmt.Printf("Data: %s\n", data[:n])

This will output (try it on the Go Playground):

Read 11 bytes
Data: Hello World
Related