How to Use io.MultiWriter in Go

Use io.MultiWriter to write identical data to multiple io.Writer destinations at the same time.

Use io.MultiWriter to write the same data to multiple destinations simultaneously by passing them as arguments to the function. In the Go source code, this is used to write output to both a buffer and os.Stderr when verbose mode is enabled.

import "io"

var buf bytes.Buffer
var w io.Writer = &buf

if cfg.BuildV {
	w = io.MultiWriter(&buf, os.Stderr)
}

fmt.Fprintf(w, "output message")