commands: Updated Command to use Response for output rather than (interface{}, error)
Matt Bell committed
Oct 10, 2014 at 12:36 UTC
b2ee05a0becfbf6a4096339c4281a6b117b4fe94
1 file changed
+16
-9
commands/command.go
+16
-9
@@ -9,7 +9,7 @@ import (
9
type Command struct {
10
Help string
11
Options []Option
12
- f func(*Request) (interface{}, error)
12
+ f func(*Request, *Response)
13
subcommands map[string]*Command
14
}
15
@@ -37,11 +37,12 @@ func (c *Command) Register(id string, sub *Command) error {
37
}
38
39
// Call invokes the command at the given subcommand path
40
-func (c *Command) Call(path []string, req *Request) (interface{}, error) {
40
+func (c *Command) Call(path []string, req *Request) *Response {
41
options := make([]Option, len(c.Options))
42
copy(options, c.Options)
43
options = append(options, globalOptions...)
44
cmd := c
45
+ res := &Response{ req: req }
46
47
if path != nil {
48
for i, id := range path {
@@ -49,7 +50,8 @@ func (c *Command) Call(path []string, req *Request) (interface{}, error) {
50
51
if cmd == nil {
52
pathS := strings.Join(path[0:i], "/")
52
- return nil, fmt.Errorf("Undefined command: '%s'", pathS)
53
+ res.SetError(fmt.Errorf("Undefined command: '%s'", pathS), Client)
54
+ return res
55
}
56
57
options = append(options, cmd.Options...)
@@ -67,24 +69,29 @@ func (c *Command) Call(path []string, req *Request) (interface{}, error) {
69
opt, ok := optionsMap[k]
70
71
if !ok {
70
- return nil, fmt.Errorf("Unrecognized command option: '%s'", k)
72
+ res.SetError(fmt.Errorf("Unrecognized command option: '%s'", k), Client)
73
+ return res
74
}
75
76
for _, name := range opt.Names {
77
if _, ok = req.options[name]; name != k && ok {
75
- return nil, fmt.Errorf("Duplicate command options were provided ('%s' and '%s')",
76
- k, name)
78
+ res.SetError(fmt.Errorf("Duplicate command options were provided ('%s' and '%s')",
79
+ k, name), Client)
80
+ return res
81
}
82
}
83
84
kind := reflect.TypeOf(v).Kind()
85
if kind != opt.Type {
82
- return nil, fmt.Errorf("Option '%s' should be type '%s', but got type '%s'",
83
- k, opt.Type.String(), kind.String())
86
+ res.SetError(fmt.Errorf("Option '%s' should be type '%s', but got type '%s'",
87
+ k, opt.Type.String(), kind.String()), Client)
88
+ return res
89
}
90
}
91
87
- return cmd.f(req)
92
+ cmd.f(req, res)
93
+
94
+ return res
95
}
96
97
// Sub returns the subcommand with the given id