Home >Backend Development >Golang >How Can I Read from the Same io.Reader Multiple Times in Go?

How Can I Read from the Same io.Reader Multiple Times in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-14 12:14:11549browse

How Can I Read from the Same io.Reader Multiple Times in Go?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn