5

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?

dreadiscool
  • 1,598
  • 3
  • 18
  • 31
  • I'm not understand. What is a "gracefully return"? Is Handle function only takes 256 length bytes? – chendesheng Jul 18 '14 at 05:20
  • 2
    You aren't dealing with `EOF` properly - see the [io.Reader](http://golang.org/pkg/io/#Reader) docs - an `EOF` can be returned with `n != 0`. Not sure whether this is your problem though! – Nick Craig-Wood Jul 18 '14 at 10:33

1 Answers1

7

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())
fabrizioM
  • 46,639
  • 15
  • 102
  • 119