Home >Backend Development >Golang >How to Read from an io.Reader Multiple Times?

How to Read from an io.Reader Multiple Times?

Barbara Streisand
Barbara StreisandOriginal
2024-12-16 14:26:18340browse

How to Read from an io.Reader Multiple Times?

How to Read from the Same io.Reader Multiple Times

When working with an io.Reader, such as request.Body, which contains data like an image, you may encounter a need to access the content multiple times. However, using ioutil.ReadAll() would consume the entire content, making subsequent reads impossible.

The Challenge

Attempting to create multiple instances of the reader, as shown in the code below, results in a nil value for the second call:

package main

import (
    "io/ioutil"
    "log"
    "strings"
)

func main() {
    r := strings.NewReader("some io.Reader stream to be read\n")
    a := &r
    b := &r
    log.Println(ioutil.ReadAll(*a))
    log.Println(ioutil.ReadAll(*b))
}

The Solution: TeeReader

To read from the same io.Reader multiple times, you can use the io.TeeReader. It duplicates the stream, allowing you to read from multiple sources simultaneously.

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))
}

Example:

In the above example, first, you create a TeeReader that reads from the original reader and a buffer. Then, you read from the TeeReader and the buffer to get the same content twice.

The above is the detailed content of How to Read from an io.Reader Multiple Times?. 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