conn, err := net.Dial("tcp", "example.com:80") if err != nil { log.Fatal(err) } defer conn.Close() _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")) if err != nil { log.Fatal(err) } conn.CloseRead() // Close the reading half of the connection // The connection can still be used to write data _, err = conn.Write([]byte("Hello, server!")) if err != nil { log.Fatal(err) }
listener, err := net.Listen("tcp", ":8080") if err != nil { log.Fatal(err) } defer listener.Close() for { conn, err := listener.Accept() if err != nil { log.Fatal(err) } go func() { defer conn.Close() // Read input from the client until CloseRead() is called buf := make([]byte, 1024) for { n, err := conn.Read(buf) if err != nil { if err == io.EOF { // Client has closed connection break } log.Println(err) return } log.Printf("Received %d bytes: %s\n", n, string(buf[:n])) } }() }This example listens for incoming TCP connections on port `8080`, accepts incoming connections, and then reads input from the client until `CloseRead()` is called. The `defer conn.Close()` line ensures that the connection will be closed properly when the function finishes. Package library: `net`