dreadiscool
dreadiscool

Reputation: 1598

Read arbitrary amount of bytes into buffer Golang

I'm trying to read a stream of info from a connection. I haven't written the server part of it, and don't have access to modifying the protocol (or else I would have made the protocol much friendlier)

I'm trying to write a service in Go that reads an arbitrary number of bytes into a buffer in a loop and passes it off to another handler (I also cannot modify this part)

This is my current setup

buf := make([]byte, 256)
for {
    n, err := conn.Read(buf)
    fmt.Println(string(buf))
    if err != nil || n== 0 {
        return
    }
    Handle(buf[:n])
}

This works fine when there are enough bytes to be read... However, at the end of the stream, there aren't 256 bytes that are readable. Is there any way to preserve my 256 byte buffer while Read() to gracefully return?

Upvotes: 6

Views: 3637

Answers (1)

fabmilo
fabmilo

Reputation: 48310

If you want to read the whole stream of the connection you could use:

   var b bytes.Buffer
   if _, err:= io.Copy(&b, conn); err != nil {
      return err
   }

   Handle(b.Bytes())

Upvotes: 9

Related Questions