MultiWriter Writes Once To Many Sinks

io.MultiWriter forwards a single Write to every destination at once, so one call can update stdout and an in-memory audit buffer identically.

GoCli Tooling

Code

gosnippet
25 lines
package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"os"
)

func main() {
	var audit bytes.Buffer
	// MultiWriter 把一次 Write 顺序写到每个目的地:stdout 与内存审计缓冲
	w := io.MultiWriter(os.Stdout, &audit)

	msg := []byte("deploy step 1 done\n")
	if _, err := w.Write(msg); err != nil {
		log.Fatal(err)
	}
	fmt.Fprintf(w, "step %d complete\n", 2)

	// 两个目的地拿到同一份内容,审计缓冲可再交给后续处理
	fmt.Println("audit captured:", audit.Len(), "bytes")
	fmt.Print("audit content: ", audit.String())
}

How the snippet works

MultiWriter Writes Once To Many Sinks comes down to the function main.

Nothing falls through silently — 1 checkpoint test err != nil on the way through.

Using it

Running the file prints labeled results such as audit captured:, audit content: — each operation’s effect is visible in the output.

Key statements

fmt.Fprintf(w, "step %d complete\n", 2)

Interactive Tools for This Topic

FAQ

What does MultiWriter Writes Once To Many Sinks print when run?
The script runs standalone; its 2 labeled outputs include `audit captured:`, `audit content:`.