Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
Problem :
You need to convert or type cast bytes.Buffer
or bytes.NewBuffer
type to io.Reader
to use in io.MultiReader()
function because of this error :
cannot use buffer_slice (type []*bytes.Buffer) as type io.Reader in argument to io.MultiReader: []*bytes.Buffer does not implement io.Reader (missing Read method).
Solution :
Wrap the bytes.Buffer
with io.Reader array
. For example :
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
)
func main() {
readerBuffer := bytes.NewBuffer([]byte("abcdefghijkl"))
readerBuffer2 := bytes.NewBuffer([]byte("mnopqrstuvwxyz"))
buff := []io.Reader{readerBuffer, readerBuffer2} // <------ here
combined := io.MultiReader(buff...)
data, _ := ioutil.ReadAll(combined)
fmt.Println(string(data))
}
or
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
)
func main() {
//readerBuffer := bytes.NewBuffer([]byte("abcdefghijkl"))
readerBuffer := &bytes.Buffer{}
readerBuffer.Write([]byte("abcdefghijkl"))
//readerBuffer2 := bytes.NewBuffer([]byte("mnopqrstuvwxyz"))
readerBuffer2 := &bytes.Buffer{}
readerBuffer2.Write([]byte("mnopqrstuvwxyz"))
buff := []io.Reader{readerBuffer, readerBuffer2} // <------ here
combined := io.MultiReader(buff...)
data, _ := ioutil.ReadAll(combined)
fmt.Println(string(data))
}
Reference :
https://socketloop.com/references/golang-io-multireader-function-example
See also : Golang : Convert(cast) []byte to io.Reader type
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.1k Golang : Byte format example
+15.2k Golang : ROT47 (Caesar cipher by 47 characters) example
+7.3k Golang : Handling Yes No Quit query input
+7.3k Golang : Rot13 and Rot5 algorithms example
+20.3k Golang : Secure(TLS) connection between server and client
+29.5k Golang : Get and Set User-Agent examples
+5.8k Golang : Experimenting with the Rejang script
+10.2k Android Studio : Simple input textbox and intercept key example
+21.9k Golang : Repeat a character by multiple of x factor
+10.7k Golang : How to transmit update file to client by HTTP request example
+5.6k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+19.8k Golang : Determine if directory is empty with os.File.Readdir() function