小能豆

How can i transform in golang io.reader to bytes.reader?

go

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?


阅读 62

收藏
2023-12-18

共1个答案

小能豆

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.

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.

2023-12-18