How to read multiple times from same io.Reader

后端 未结 4 1868
一整个雨季
一整个雨季 2020-12-14 14:33

I want to use request.Body(type io.ReadCloser) which is containing a image.

I dont want to use ioutil.ReadAll() as i want to write this bod

4条回答
  •  旧巷少年郎
    2020-12-14 14:57

    Technically, on one reader, you cannot read multiple times.

    • Even if you create different references but
    • when you read once it will be same object referred by all references.
    • so what you can do is read the content and store it in one variable.
    • Then use that variable as many times as you want.

    This will print twice.

    package main
    
    import (
        "io/ioutil"
        "log"
        "strings"
    )
    
    func main() {
        r := strings.NewReader("some io.Reader stream to be read\n")
        stringData, _ := ioutil.ReadAll(r)
        log.Println(stringData)
        log.Println(stringData)
    }
    

提交回复
热议问题