2

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 ?

2
  • 1
    What are you trying to do? The argument to net.Buffers.Read is a destination slice. You've not written anything to the buffer, and are asking for a 5-byte read -- hence EOF. Even if the read succeeded, the destination slice is unnamed, so couldn't be read. Feb 5, 2021 at 11:21
  • 1
    I guess you think Read reads a string into the buffer, rather than reads a string out of the buffer. Write writes a string into the buffer. Feb 5, 2021 at 11:25

1 Answer 1

2

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
1
  • 1
    Thanks, what I Was looking for is the append(...) call to populate the net.Buffers
    – Curious
    Feb 5, 2021 at 11:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.