#How to use io.Reader & io.ReaderFrom?

3 messages · Page 1 of 1 (latest)

empty reef
#

I got a http response body, which is a io.ReadCloser and I'm trying to copy the. response to a new io.Reader. My best attempt is to use a ReaderFrom / buffer, but I'd have to change the signature of the http call method.
In short i'd just like a method that looks like this, without having to do lots of converts? I might just not grasp the io interface world yet..

func read(ctx context.Context, url string, h headers) (io.Reader, error) {
    c := http.Client{
        Timeout: 4 * time.Second,
    }

    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return nil, err
    }

    for k, v := range h {
        req.Header.Add(k, v)
    }

    var res *http.Response
    res, err = c.Do(req)
    if err != nil {
        return nil, err
    }
    defer res.Body.Close()

    var buf io.ReaderFrom
    if _, err = buf.ReadFrom(res.Body); err != nil {
        return nil, err
    }

        // Not a io.Reader, doesnt implement Read
    return buf, nil
}```
void night
#
var buf bytes.Buffer
if _, err = io.Copy(&buf, res.Body); err != nil {
  return nil, err
}
#

you need an instance of the implementation instead of var x theinterface