Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what are the return values of a http.Hijacker?

Tags:

go

A http.Hijacker as defined in the Go standard library has a Hijack() method, with the following signature:

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

What is the meaning of the first two return values? Both the net.Conn and the *bufio.ReadWriter have Write() methods. What is the difference between the two? Which one should I use to send data to the network?

like image 519
jochen Avatar asked Sep 03 '19 20:09

jochen


1 Answers

The returned net.Conn is the underlying io.Reader for the ReadWriter.Reader and the underlying io.Writer for the ReadWriter.Writer.

The ReadWriter.Reader can contain data buffered from the client. The ReadWriter.Writer is created in the Hijack implementation and can be ignored.

If the application is reading from the client and it's possible that the client data is buffered, then the application must read at least Reader.Buffered() bytes from the ReadWriter.Reader before reading directly from the net.Conn.

If the application is going to use the bufio package to buffer network IO, then the application can reduce the number of memory allocations by using the returned bufio.Reader and bufio.Writer.

Otherwise, the application can use the net.Conn directly for read and write.

If the application does use the bufio.Writer instead of writing directly to the net.Conn, then the application may need to explicitly flush the buffer with a call to Writer.Flush.

The application must use the net.Conn to close the connection and set deadlines.

In an earlier version of the net/http package, the server used a bufio.Writer for network IO and returned that bufio.Writer from the Hijack method. When the implementation was changed to use a different buffering mechanism, the creation of the bufio.Writer was moved to the Hijack method.

Some examples:

Server sent events: The ReadWriter.Reader can be ignored because the application will not read from the connection. Use the ReadWriter.Writer to reduce allocations.

WebSockets: It is an error for the client to send data after sending the handshake request and before receiving the handshake response. Given this, data should not be buffered in the ReadWriter.Reader. The application can choose to ignore the ReadWriter.Reader after possibly checking for unexpected data using Reader.Buffered() != 0.

like image 126
Bayta Darell Avatar answered Oct 18 '22 02:10

Bayta Darell