4

When using Hijack() with a http.ResponseWriter instance

Hijack() (net.Conn, *bufio.ReadWriter, error)

What is the difference between reading from the net.Conn and the *bufio.ReadWriter?

Michael
  • 41,989
  • 11
  • 82
  • 128
Kim Byer
  • 283
  • 1
  • 4
  • 12
  • 2
    The `*bufio.ReadWriter` is buffer IO for the underlying `net.Conn`. Are you asking *why* you would use buffered Reads? – JimB Feb 22 '16 at 20:15
  • Ahh I see. No I was just confused why there is two ways of getting the same data... :) thanks! – Kim Byer Feb 22 '16 at 20:20

2 Answers2

5

net.Conn.Read and *bufio.ReadWriter.Read both read from the same connection, but the latter is buffered. The Hijack method in the standard "net/http" package directly returns the net.Conn wrapped in a bufio.ReadWriter, using the same *bufio.Reader that was already allocated for the http request.

It's possible that there is still data buffered in the bufio.Reader which you may miss when reading directly from the network connection. If you want to use the net.Conn directly, you should check if there is buffered data already with Reader.Buffered, and handle that according to the protocol being used.

In general, you should prefer to use bufio.ReadWriter, as it will be more efficient for non-optimally sized reads and writes to the network.

The net.Conn is still needed to handle the Read and Write deadlines, to close the net.Conn when you're done, and for any other network-specific activities.

JimB
  • 104,193
  • 13
  • 262
  • 255
  • 1
    If the protocol is such that the client must wait for a response from the server before writing data after the HTTP request header, then the server application can ignore the bufio wrapper after [checking for a client error](https://godoc.org/bufio#Reader.Buffered). The websocket protocol is an example of where this can be done. – Charlie Tumahai Feb 22 '16 at 21:01
  • Thanks a lot guys! I'm new to go and people like you encourage me to not give up! I really appreciate it! Thanks again! – Kim Byer Feb 22 '16 at 22:19
-1

Their difference is buffered IO.

net.Conn implements Read() and Write() thus implementing io.Reader and io.Writer. This is why bufio can wrap it up as a buffered ReadWriter and further implement functions on top using those two methods in a buffered manner.

If you only want to use Read() and Write(), you can just stick with net.Conn, otherwise you can take advantage for the buffered ReadWriter methods.

See https://golang.org/pkg/io/#Reader and https://golang.org/pkg/io/#Writer

d1str0
  • 235
  • 1
  • 11