I have the next code:
func Decompress(input []byte, ctx context.Context) (jsonMap map[string]string) { dataReaders := SplitDataByPreamble(input) jsonMap = map[string]string{} for _, reader := range dataReaders { select { case <-ctx.Done(): { log.Println(ctx.Err()) return jsonMap } default: { key := GetKey(&reader) keyString := string(key) var value string f, ok := keyAndStrangeValues[keyString] if ok { value = f(&reader) } else { value = parseString(&reader) } jsonMap[keyString] = value } } } return }
and the next function:
func SplitDataByPreamble(input []byte) (readers []bytes.Reader) { m := regexp.MustCompile(string(input[0:2]) + "." + string(input[3:4])) foundData := m.FindAll(input, -1) if len(foundData) <= 0 { log.Fatalln("Cannot split data!") } for _, data := range foundData { r := bytes.NewReader(data) readers = append(readers, r) } return }
At last function, i want to return a slice of bytes.Reader. But next function return io.Reader
r := bytes.NewReader(data)
And cause the situation in the first code i get errors. How can i transorm io.reader to bytes.reader?
In Go, you can’t directly convert an io.Reader to a bytes.Reader because the bytes.Reader type is specifically designed to work with a byte slice ([]byte). However, you can read the data from the io.Reader into a byte slice and then create a bytes.Reader from that slice.
io.Reader
bytes.Reader
[]byte
Here’s an example:
func createBytesReaderFromIOReader(input io.Reader) (*bytes.Reader, error) { // Read data from the io.Reader into a byte slice data, err := ioutil.ReadAll(input) if err != nil { return nil, err } // Create a bytes.Reader from the byte slice reader := bytes.NewReader(data) return reader, nil }
You can then use this function to convert an io.Reader to a bytes.Reader:
r := bytes.NewReader(data) bytesReader, err := createBytesReaderFromIOReader(r) if err != nil { log.Fatal(err) } // Now you can use bytesReader as a *bytes.Reader
In your specific case, you can modify your SplitDataByPreamble function to return []io.Reader instead of []bytes.Reader. Then, when you need to use the readers in the Decompress function, you can use the createBytesReaderFromIOReader function to convert each io.Reader to a *bytes.Reader.
SplitDataByPreamble
[]io.Reader
[]bytes.Reader
Decompress
createBytesReaderFromIOReader
*bytes.Reader