-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
98 lines (83 loc) · 2.33 KB
/
command.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package cuckooc
import (
"fmt"
"strings"
)
// Executor executes command/command-set on a given filter
// and responds with a result
type Executor interface {
FilterName() string
GetAction() string
Execute(config Config, f *filter) (result string, err error)
Respond(result string, debug bool, err error)
}
// command refers to single command to be performed on the filter using args provided
// and a Response channel to receive the execution result
type command struct {
Filter string
Action string
Args []string
ResponseChan chan<- string
}
// FilterName returns the name of the filter
func (c command) FilterName() string {
return c.Filter
}
// GetAction returns the action of the command
func (c command) GetAction() string {
return c.Action
}
// Respond sends the result/error over the response chan
// false if error
func (c command) Respond(result string, debug bool, err error) {
if err != nil {
result = notOk
if debug {
result = fmt.Sprintf("%s(%v)", notOk, err)
}
}
c.ResponseChan <- result
}
// Execute fetches the appropriate action handler and executes the action on filter
func (c command) Execute(config Config, f *filter) (result string, err error) {
ah, ok := handlerMux[c.Action]
if !ok {
return result, fmt.Errorf("unknown action: %s", c.Action)
}
return ah(config, f, c.Args)
}
// parseCommand parses the cmd and returns an command
//
// Format of the command is as follows
// [filter name] [action] [args...]
// command requires at least filter-name and an action
func parseCommand(cmd string, respChan chan<- string) (*command, error) {
var args []string
for _, arg := range strings.Split(strings.TrimSpace(cmd), " ") {
arg = strings.TrimSpace(arg)
if arg == "" {
continue
}
args = append(args, arg)
}
if len(args) < 2 {
return nil, fmt.Errorf("require atleast 2 arguments")
}
return &command{
Filter: strings.ToLower(args[0]),
Action: strings.ToLower(args[1]),
Args: args[2:],
ResponseChan: respChan,
}, nil
}
// readCommands will read the data and returns the string commands back
//
// multiple commands can be sent in through tcp/udp data with \n as a delimiter
// TODO(ved): support command set
func readCommands(data []byte) []string {
if len(data) < 1 {
return nil
}
s := strings.TrimSpace(string(data))
return strings.Split(s, "\n")
}