mirror of
https://github.com/ipfs/kubo.git
synced 2025-07-03 13:00:37 +08:00
commands: Made Response implement io.Reader
This commit is contained in:

committed by
Juan Batiz-Benet

parent
94683bb6b2
commit
3cebd2176e
@ -1,9 +1,11 @@
|
|||||||
package commands
|
package commands
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"encoding/xml"
|
"encoding/xml"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -49,6 +51,8 @@ var marshallers = map[EncodingType]Marshaller{
|
|||||||
// Response is the result of a command request. Handlers write to the response,
|
// Response is the result of a command request. Handlers write to the response,
|
||||||
// setting Error or Value. Response is returned to the client.
|
// setting Error or Value. Response is returned to the client.
|
||||||
type Response interface {
|
type Response interface {
|
||||||
|
io.Reader
|
||||||
|
|
||||||
Request() Request
|
Request() Request
|
||||||
|
|
||||||
// Set/Return the response Error
|
// Set/Return the response Error
|
||||||
@ -68,6 +72,7 @@ type response struct {
|
|||||||
req Request
|
req Request
|
||||||
err *Error
|
err *Error
|
||||||
value interface{}
|
value interface{}
|
||||||
|
out io.Reader
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *response) Request() Request {
|
func (r *response) Request() Request {
|
||||||
@ -112,6 +117,30 @@ func (r *response) Marshal() ([]byte, error) {
|
|||||||
return marshaller(r.value)
|
return marshaller(r.value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *response) Read(p []byte) (int, error) {
|
||||||
|
// if command set value to a io.Reader, set that as our output stream
|
||||||
|
if r.out == nil {
|
||||||
|
if out, ok := r.value.(io.Reader); ok {
|
||||||
|
r.out = out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// if there is an output stream set, read from it
|
||||||
|
if r.out != nil {
|
||||||
|
return r.out.Read(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// no stream set, so marshal the error or value
|
||||||
|
output, err := r.Marshal()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// then create a Reader from the marshalled data, and use it as our output stream
|
||||||
|
r.out = bytes.NewReader(output)
|
||||||
|
return r.out.Read(p)
|
||||||
|
}
|
||||||
|
|
||||||
// NewResponse returns a response to match given Request
|
// NewResponse returns a response to match given Request
|
||||||
func NewResponse(req Request) Response {
|
func NewResponse(req Request) Response {
|
||||||
return &response{req: req}
|
return &response{req: req}
|
||||||
|
Reference in New Issue
Block a user