When working with an io.ReadCloser type like request.Body, it can be problematic when wanting to perform multiple operations (e.g., write to a file and decode). Direct calls to ioutil.ReadAll() consume the entire stream, making subsequent operations impossible.
Unlike direct reads, io.TeeReader allows users to duplicate an io.Reader stream, enabling multiple references to the same content. This solves the problem of reading the same data twice.
Here's an implementation using io.TeeReader:
package main import ( "bytes" "io" "io/ioutil" "log" "strings" ) func main() { r := strings.NewReader("io.Reader contents to be read") var buf bytes.Buffer tee := io.TeeReader(r, &buf) // Perform the first operation using tee. log.Println(ioutil.ReadAll(tee)) // Perform the second operation using the duplicated content in the buffer. log.Println(ioutil.ReadAll(&buf)) }
The above is the detailed content of How Can I Duplicate an io.Reader for Multiple Read Operations in Go?. For more information, please follow other related articles on the PHP Chinese website!