Skip to content

Commit

Permalink
Introduce DecodeStreamer for Client.Do
Browse files Browse the repository at this point in the history
This enables a client to stream values out of the HTTP response. It does
so by providing a result that implements DecodeStreamer with something
like the following.  Error handling has been omitted for clarity.

    // DecodeStream decodes and processes each record of a JSON array
    func (streamingDecoder) DecodeStream(r io.Reader) error {
        dec := json.NewDecoder(r)
        tok, _ := dec.Token() // want: json.Delim('[')
        for dec.More() {
            _ = dec.Decode(&record)
            // do something with record
        }
        tok, _ = dec.Token() // want: json.Delim(']')
        _, err = dec.Token() // want: io.EOF
        return nil
    }
  • Loading branch information
MichaelUrman committed May 28, 2021
1 parent 7b4e7fa commit aef5369
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions druid.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
Expand Down Expand Up @@ -133,6 +134,8 @@ func (c *Client) NewRequest(method, path string, opt interface{}) (*retryablehtt
return r, nil
}

type DecodeStreamer interface{ DecodeStream(io.Reader) error }

func (c *Client) Do(r *retryablehttp.Request, result interface{}) (*Response, error) {
resp, err := c.http.Do(r)
if err != nil {
Expand All @@ -144,6 +147,9 @@ func (c *Client) Do(r *retryablehttp.Request, result interface{}) (*Response, er
return nil, err
}
if result != nil {
if decoder, ok := result.(DecodeStreamer); ok {
return nil, decoder.DecodeStream(resp.Body)
}
if err = json.NewDecoder(resp.Body).Decode(result); err != nil {
return nil, err
}
Expand Down

0 comments on commit aef5369

Please sign in to comment.