mirror of
https://github.com/ipfs/kubo.git
synced 2025-06-19 01:39:35 +08:00
commands: Ensure command output is correct type (if cmd.Type is set), resolves #321
This commit is contained in:

committed by
Juan Batiz-Benet

parent
c973776049
commit
3b407c705d
@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
u "github.com/jbenet/go-ipfs/util"
|
||||
@ -64,6 +65,8 @@ var ErrNotCallable = errors.New("This command can't be called directly. Try one
|
||||
|
||||
var ErrNoFormatter = errors.New("This command cannot be formatted to plain text")
|
||||
|
||||
var ErrIncorrectType = errors.New("The command returned a value with a different type than expected")
|
||||
|
||||
// Call invokes the command for the given Request
|
||||
func (c *Command) Call(req Request) Response {
|
||||
res := NewResponse(req)
|
||||
@ -106,6 +109,17 @@ func (c *Command) Call(req Request) Response {
|
||||
return res
|
||||
}
|
||||
|
||||
// If the command specified an output type, ensure the actual value returned is of that type
|
||||
if cmd.Type != nil {
|
||||
definedType := reflect.ValueOf(cmd.Type).Type()
|
||||
actualType := reflect.ValueOf(output).Type()
|
||||
|
||||
if definedType != actualType {
|
||||
res.SetError(ErrIncorrectType, ErrNormal)
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
// clean up the request (close the readers, e.g. fileargs)
|
||||
// NOTE: this means commands can't expect to keep reading after cmd.Run returns (in a goroutine)
|
||||
err = req.Cleanup()
|
||||
|
Reference in New Issue
Block a user