/
gcmd_parser_handler.go
59 lines (53 loc) · 1.61 KB
/
gcmd_parser_handler.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
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
//
package gcmd
import (
"github.com/gogf/gf/errors/gcode"
"github.com/gogf/gf/errors/gerror"
)
// BindHandle registers callback function <f> with <cmd>.
func (p *Parser) BindHandle(cmd string, f func()) error {
if _, ok := p.commandFuncMap[cmd]; ok {
return gerror.NewCode(gcode.CodeInvalidOperation, "duplicated handle for command:"+cmd)
} else {
p.commandFuncMap[cmd] = f
}
return nil
}
// BindHandleMap registers callback function with map <m>.
func (p *Parser) BindHandleMap(m map[string]func()) error {
var err error
for k, v := range m {
if err = p.BindHandle(k, v); err != nil {
return err
}
}
return err
}
// RunHandle executes the callback function registered by <cmd>.
func (p *Parser) RunHandle(cmd string) error {
if handle, ok := p.commandFuncMap[cmd]; ok {
handle()
} else {
return gerror.NewCode(gcode.CodeMissingConfiguration, "no handle found for command:"+cmd)
}
return nil
}
// AutoRun automatically recognizes and executes the callback function
// by value of index 0 (the first console parameter).
func (p *Parser) AutoRun() error {
if cmd := p.GetArg(1); cmd != "" {
if handle, ok := p.commandFuncMap[cmd]; ok {
handle()
} else {
return gerror.NewCode(gcode.CodeMissingConfiguration, "no handle found for command:"+cmd)
}
} else {
return gerror.NewCode(gcode.CodeMissingParameter, "no command found")
}
return nil
}