Home > Backend Development > Golang > Convert from `bufio.Reader` to `io.ReadWriteCloser`

Convert from `bufio.Reader` to `io.ReadWriteCloser`

王林
Release: 2024-02-05 22:48:07
forward
1010 people have browsed it

从 `bufio.Reader` 转换为 `io.ReadWriteCloser`

Question content

I have a io.readwritecloser and I want to peek into it without advancing the reader,

So I'm using

bi := bufio.NewReader(i)
bi.Peek(1)
Copy after login

So far so good, but then when I want to reuse the original io.readwritecloser (i) it only has eof.

So my question is how to convert from bufio.reader back to io.readwritecloser


Correct answer


Because bufio.reader buffers data from the underlying reader, the application must read data from bufio.reader after calling peek.

To get an io.readwritecloser that does this, wrap bufio.reader and the original io.readwritecloser:

// bufferedreadwritecloser has all of the methods
// from *bufio.reader and io.readwritecloser.
type bufferedreadwritecloser struct {
    *bufio.reader
    io.readwritecloser
}

func (rw *bufferedreadwritecloser) read(p []byte) (int, error) {
    return rw.reader.read(p)
}
Copy after login

Usage is as follows:

rw := &BufferedReadWriteCloser{bufio.NewReader(i), i}
p, err := rw.Peek(1)
Copy after login
The value of

rw satisfies the io.readwritecloser interface.

Does not require or assume that io.readwritecloser has a seek method.

The above is the detailed content of Convert from `bufio.Reader` to `io.ReadWriteCloser`. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template