Handling Multiple Reads from the Same io.Reader
Reading from an io.Reader stream can only be done once, as it represents a sequential data stream. However, there are scenarios where you might need to read the same data from multiple sources.
One way to achieve this is by using io.TeeReader. This function creates a new io.Reader that duplicates the input data, allowing you to create multiple instances with separate references to the original stream.
For example:
package main import ( "bytes" "io" "io/ioutil" "log" "strings" ) func main() { r := strings.NewReader("some io.Reader stream to be read\n") var buf bytes.Buffer tee := io.TeeReader(r, &buf) log.Println(ioutil.ReadAll(tee)) log.Println(ioutil.ReadAll(&buf)) }
In this example, ioutil.ReadAll() is first called on tee, which reads and logs the data from the original stream. Then, ioutil.ReadAll() is called on &buf, which prints the copy of the data from the TeeReader.
Note: It's important to read from tee before attempting to read from buf. Otherwise, the buffer will be empty.
The above is the detailed content of How Can I Read from the Same io.Reader Multiple Times in Go?. For more information, please follow other related articles on the PHP Chinese website!