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.

GoData Fetching

Code

gosnippet
33 lines
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

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.