Skip to content

Commit

Permalink
Added JSON streaming callback
Browse files Browse the repository at this point in the history
  • Loading branch information
djthorpe committed Jul 27, 2024
1 parent b8e9bcb commit 78c4a59
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
21 changes: 19 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"mime"
Expand Down Expand Up @@ -47,6 +48,10 @@ type Client struct {

type ClientOpt func(*Client) error

// Callback for json stream events, return an error if you want to stop streaming
// with an error and io.EOF if you want to stop streaming and return success
type JsonStreamCallback func(v any) error

///////////////////////////////////////////////////////////////////////////////
// GLOBALS

Expand Down Expand Up @@ -302,8 +307,20 @@ func do(client *http.Client, req *http.Request, accept string, strict bool, out
// Decode the body
switch mimetype {
case ContentTypeJson:
if err := json.NewDecoder(response.Body).Decode(out); err != nil {
return err
// JSON decode is streamable
dec := json.NewDecoder(response.Body)
for {
if err := dec.Decode(out); err == io.EOF {
break
} else if err != nil {
return err
} else if reqopts.jsonStreamCallback != nil {
if err := reqopts.jsonStreamCallback(out); errors.Is(err, io.EOF) {
break
} else if err != nil {
return err
}
}
}
case ContentTypeTextStream:
if err := NewTextStream().Decode(response.Body, reqopts.textStreamCallback); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion pkg/multipart/multipart.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func NewMultipartEncoder(w io.Writer) *Encoder {
}
}

// NewFormEncoder creates a new encoder object, whichwrites
// NewFormEncoder creates a new encoder object, which writes
// application/x-www-form-urlencoded to the io.Writer
func NewFormEncoder(w io.Writer) *Encoder {
return &Encoder{
Expand Down
9 changes: 9 additions & 0 deletions requestopts.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type requestOpts struct {
*http.Request
noTimeout bool // OptNoTimeout
textStreamCallback TextStreamCallback // OptTextStreamCallback
jsonStreamCallback JsonStreamCallback // OptJsonStreamCallback
}

type RequestOpt func(*requestOpts) error
Expand Down Expand Up @@ -103,3 +104,11 @@ func OptTextStreamCallback(fn TextStreamCallback) RequestOpt {
return nil
}
}

// OptJsonStreamCallback is called for each decoded JSON event
func OptJsonStreamCallback(fn JsonStreamCallback) RequestOpt {
return func(r *requestOpts) error {
r.jsonStreamCallback = fn
return nil
}
}

0 comments on commit 78c4a59

Please sign in to comment.