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.
Code
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
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.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.