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:
import (
"context"
"net"
"time"
)
context.Context
using the context.WithTimeout
function:ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) // Timeout after 5 seconds
defer cancel()
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
}
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()
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
// 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.