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

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

王林
王林forward
2024-02-05 22:48:07888browse

从 `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)

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

Usage is as follows:

rw := &BufferedReadWriteCloser{bufio.NewReader(i), i}
p, err := rw.Peek(1)
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:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete