Net Pipe In-Memory Connection
Connect two goroutines with net.Pipe, an in-memory synchronous connection that needs no listener, and exchange one framed line before closing.
Code
package main
import (
"bufio"
"fmt"
"net"
"time"
)
func main() {
// net.Pipe returns two ends of an in-memory connection, no port involved
client, server := net.Pipe()
defer client.Close()
defer server.Close()
go func() {
// the write blocks until the other end reads
fmt.Fprintln(server, "hello over the pipe")
server.Close()
}()
client.SetReadDeadline(time.Now().Add(time.Second))
line, err := bufio.NewReader(client).ReadString('\n')
if err != nil {
fmt.Println("read failed:", err)
return
}
fmt.Print("received: ", line)
// after the peer closes, further writes report ErrClosedPipe
_, err = client.Write([]byte("late reply"))
fmt.Println("write after close:", err)
}Order of operations
The action concentrates in the function main — everything else is wiring.
err is inspected at 1 call site before any result is trusted. Work is dispatched on a goroutine. Cleanup is attached with defer, so it runs on every exit path of the function.
Watch out for
- The dependency list is empty; the language runtime covers it all.
Applying it
The declaration at the core: func main()
Output lines are prefixed (read failed:, received:, write after close:), which keeps each step and its output line joined.
Statements that matter
if err != nil {
fmt.Println("read failed:", err)
return
}
defer client.Close()
defer server.Close()
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.
FAQ
- What does Net Pipe In-Memory Connection print when run?
- No setup needed: run the file and look for labeled lines like `read failed:`, `received:`, `write after close:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.