I'm writing some code that needs functionality that is almost satisfied by the ReadBytes
method in the bufio
package. Specifically, that method reads from a Reader
until it encounters a particular byte. I need something that reads till it encounters one out of couple of bytes (space, newline and tab mainly).
I looked at the source for the library and I know what to do if I have access to the internal buffer used by bufio
structs. Is there any way I could "monkey patch" the package and add another method or two to it? Or another way to get the functionality I need?
Something along this approach (caution: untested code):
type reader struct{
*bufio.Reader // 'reader' inherits all bufio.Reader methods
}
func newReader(rd io.Reader) reader {
return reader{bufio.NewReader(rd)}
}
// Override bufio.Reader.ReadBytes
func (r reader) ReadBytes(delim byte) (line []byte, err error) {
// here goes the monkey patch
}
// Or
// Add a new method to bufio.Reader
func (r reader) ReadBytesEx(delims []byte) (line []byte, err error) {
// here goes the new code
}
EDIT: I should have noted that this doesn't help to access the original package internals (non exported entities). Thanks Abhay for pointing that out in your comment.
It's usually best to solve problems using the package API. If you have a compelling reason to access unexported features though, copy the package source and hack it up. The BSD-style license as about as liberal as they come.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With