How to implement custom I/O timeouts and deadlines in Go?

To implement custom I/O timeouts and deadlines in Go, you can use the context package along with the net and time packages. Here's a step-by-step guide:

  1. Import the required packages:
import ( "context" "net" "time" )
  1. Create a new context.Context using the context.WithTimeout function:
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) // Timeout after 5 seconds defer cancel()
  1. Create a net.Dialer with the desired timeout value:
dialer := &net.Dialer{ Timeout: time.Second * 5, // Timeout after 5 seconds Deadline: time.Now().Add(time.Second * 10), // Deadline after 10 seconds }
  1. Use the context and net.Dialer to establish a connection:
conn, err := dialer.DialContext(ctx, "tcp", "example.com:80") if err != nil { // handle error } defer conn.Close()
  1. You can also set read and write deadlines on the connection if needed:
conn.SetReadDeadline(time.Now().Add(time.Second * 5)) // Read deadline after 5 seconds conn.SetWriteDeadline(time.Now().Add(time.Second * 5)) // Write deadline after 5 seconds
  1. Now you can perform read and write operations on the connection using the configured timeouts and deadlines:
// Read operation buffer := make([]byte, 1024) n, err := conn.Read(buffer) if err != nil { // handle error } fmt.Printf("Received %d bytes: %s\n", n, string(buffer[:n])) // Write operation _, err := conn.Write([]byte("Hello, server")) if err != nil { // handle error }

By using the context package and configuring the Timeout and Deadline properties in the net.Dialer, you can easily implement custom I/O timeouts and deadlines in Go. The context.WithTimeout function allows you to create a timeout context, ensuring that operations are canceled if they exceed the specified timeout duration.