package main import ( "net" "time" ) func main() { // Dial a TCP connection to a server conn, err := net.Dial("tcp", "example.com:80") if err != nil { panic(err) } // Set a write deadline of 5 seconds err = conn.SetWriteDeadline(time.Now().Add(5 * time.Second)) if err != nil { panic(err) } // Write some data to the connection _, err = conn.Write([]byte("Hello, world!")) if err != nil { panic(err) } }
package main import ( "net" "os" "time" ) func main() { // Listen for incoming connections on a TCP address listener, err := net.Listen("tcp", "localhost:8080") if err != nil { panic(err) } defer listener.Close() for { // Accept a new connection from a client conn, err := listener.Accept() if err != nil { panic(err) } // Set a write deadline of 10 seconds on the connection err = conn.SetWriteDeadline(time.Now().Add(10 * time.Second)) if err != nil { panic(err) } // Write the contents of a file to the connection file, err := os.Open("/path/to/file.txt") if err != nil { panic(err) } defer file.Close() _, err = file.WriteTo(conn) if err != nil { panic(err) } // Close the connection conn.Close() } }In this example, we listen for incoming connections on a TCP address. When a client connects, we call `SetWriteDeadline` to set a write deadline of 10 seconds on the connection. We then write the contents of a file to the connection using the `WriteTo` method. If the write operation takes longer than 10 seconds, it will return a timeout error. The Go net package provides support for various network protocols and facilities for building network servers and clients.