Read reads data from the connection. As Read calls [Conn.Handshake], in order to prevent indefinite blocking a deadline must be set for both Read and [Conn.Write] before Read is called when the handshake has not yet completed. See [Conn.SetDeadline], [Conn.SetReadDeadline], and [Conn.SetWriteDeadli
(b []byte)
| 1442 | // has not yet completed. See [Conn.SetDeadline], [Conn.SetReadDeadline], and |
| 1443 | // [Conn.SetWriteDeadline]. |
| 1444 | func (c *Conn) Read(b []byte) (int, error) { |
| 1445 | if err := c.Handshake(); err != nil { |
| 1446 | return 0, err |
| 1447 | } |
| 1448 | if len(b) == 0 { |
| 1449 | // Put this after Handshake, in case people were calling |
| 1450 | // Read(nil) for the side effect of the Handshake. |
| 1451 | return 0, nil |
| 1452 | } |
| 1453 | |
| 1454 | c.in.Lock() |
| 1455 | defer c.in.Unlock() |
| 1456 | |
| 1457 | for c.input.Len() == 0 { |
| 1458 | if err := c.readRecord(); err != nil { |
| 1459 | return 0, err |
| 1460 | } |
| 1461 | for c.hand.Len() > 0 { |
| 1462 | if err := c.handlePostHandshakeMessage(); err != nil { |
| 1463 | return 0, err |
| 1464 | } |
| 1465 | } |
| 1466 | } |
| 1467 | |
| 1468 | n, _ := c.input.Read(b) |
| 1469 | |
| 1470 | // If a close-notify alert is waiting, read it so that we can return (n, |
| 1471 | // EOF) instead of (n, nil), to signal to the HTTP response reading |
| 1472 | // goroutine that the connection is now closed. This eliminates a race |
| 1473 | // where the HTTP response reading goroutine would otherwise not observe |
| 1474 | // the EOF until its next read, by which time a client goroutine might |
| 1475 | // have already tried to reuse the HTTP connection for a new request. |
| 1476 | // See https://golang.org/cl/76400046 and https://golang.org/issue/3514 |
| 1477 | if n != 0 && c.input.Len() == 0 && c.rawInput.Len() > 0 && |
| 1478 | recordType(c.rawInput.Bytes()[0]) == recordTypeAlert { |
| 1479 | if err := c.readRecord(); err != nil { |
| 1480 | return n, err // will be io.EOF on closeNotify |
| 1481 | } |
| 1482 | } |
| 1483 | |
| 1484 | return n, nil |
| 1485 | } |
| 1486 | |
| 1487 | // Close closes the connection. |
| 1488 | func (c *Conn) Close() error { |
no test coverage detected