How to Work with Unix Pipes in Go

Create a Unix pipe in Go using os.Pipe() to connect a writer and reader for streaming data between goroutines.

Use os.Pipe() to create a pipe and io.Copy() to transfer data between the reader and writer ends. This connects two goroutines or processes so the output of one becomes the input of the other.

package main

import (
	"io"
	"os"
)

func main() {
	// Create a pipe
	reader, writer, err := os.Pipe()
	if err != nil {
		panic(err)
	}

	// Write data to the pipe
	go func() {
		defer writer.Close()
		writer.Write([]byte("Hello, pipe!"))
	}()

	// Read data from the pipe
	data, err := io.ReadAll(reader)
	if err != nil {
		panic(err)
	}
	println(string(data))
	reader.Close()
}