The io.Pipe package in Go provides a way to create an in-memory pipe that allows for inter-goroutine communication and data streaming. Here's how you can use it:
import (
"io"
"fmt"
)
io.Pipe()
:reader, writer := io.Pipe()
go func() {
defer writer.Close()
data := []byte("Hello, World!")
_, err := writer.Write(data)
if err != nil {
fmt.Println("Write error:", err)
}
}()
go func() {
defer reader.Close()
buf := make([]byte, 1024)
n, err := reader.Read(buf)
if err != nil {
fmt.Println("Read error:", err)
}
fmt.Println(string(buf[:n])) // Print the received data
}()
// Here, you can use a sync.WaitGroup or sleep for some time to allow the goroutines to complete their tasks
Hello, World!
By using the io.Pipe, you can establish a communication channel between goroutines, making it easier to pass data or stream it between them. Remember to properly close the reader and writer to avoid resource leaks.