How to create and use custom I/O streams (e.g., using sockets or pipes) in Go?

In Go, you can create and use custom I/O streams using sockets or pipes by implementing the io.Reader and io.Writer interfaces. Here's how you can do it:

Using Sockets:

  1. Import the required packages:
import ( "net" "io" )
  1. Create a net.Listener to listen on a specific network address:
listener, err := net.Listen("tcp", "localhost:8080") if err != nil { // handle error } defer listener.Close()
  1. Accept incoming connections on the listener:
conn, err := listener.Accept() if err != nil { // handle error } defer conn.Close()
  1. Use the conn object to read from/write to the socket connection:
// Read from the socket connection buffer := make([]byte, 1024) n, err := conn.Read(buffer) if err != nil { // handle error } data := buffer[:n] // Write to the socket connection n, err = conn.Write([]byte("Hello, client!")) if err != nil { // handle error }

Using Pipes:

  1. Import the required packages:
import ( "io" "os" )
  1. Create a pipe using io.Pipe():
reader, writer := io.Pipe() defer reader.Close() defer writer.Close()
  1. Use the reader and writer objects for reading and writing:
// Write to the pipe go func() { _, err := writer.Write([]byte("Data from writer")) if err != nil { // handle error } writer.Close() }() // Read from the pipe buffer := make([]byte, 1024) n, err := reader.Read(buffer) if err != nil { // handle error } data := buffer[:n]

These are basic examples to get you started with custom I/O streams using sockets and pipes in Go. You can use these concepts and build more complex functionality as per your requirements.