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
+14.2k Golang : GUI with Qt and OpenCV to capture image from camera
+16.1k Golang : Convert slice to array
+9.2k Golang : How to extract video or image files from html source code
+7.7k Golang : Handle Palindrome string with case sensitivity and unicode
+15.2k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+8k Golang : Emulate NumPy way of creating matrix example
+13.6k Golang : convert(cast) string to float value
+10.8k Golang : Create S3 bucket with official aws-sdk-go package
+7.6k Javascript : Put image into Chrome browser's console
+6.6k Golang : Decode XML data from RSS feed
+20.8k Golang : Create and resolve(read) symbolic links
+10.4k Golang : Underscore string example