-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnew.go
78 lines (56 loc) · 1.62 KB
/
new.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
package termfx
import (
"io"
"sync"
"github.com/pkg/errors"
)
var (
//ErrFunctionAlreadyRegistered is returned after a command name conflict of a function
ErrFunctionAlreadyRegistered = errors.New("function with the same name has already been registered")
)
//RegistryFunction is used to register a function e.g. func(name: "exit", func) can be called as exit()
type RegistryFunction func(session io.Writer, args string) (int, error)
//Registry contains all the registed commands and variables
type Registry struct {
commands map[string]RegistryFunction
split []string
mutex sync.Mutex
}
//New creates a new registry which can be used to register event call backs
func New(split ...string) *Registry {
var CustomSplit = []string{"<<", ">>"}
if len(split) > 1 {
CustomSplit[0] = split[0]
CustomSplit[1] = split[1]
}
return &Registry{
commands: make(map[string]RegistryFunction),
split: CustomSplit,
}
}
//RegisterFunction will add the function to the registry
func (r *Registry) RegisterFunction(name string, function RegistryFunction) error {
name += "()"
r.mutex.Lock()
defer r.mutex.Unlock()
_, ok := r.commands[name]
if ok == true {
return ErrFunctionAlreadyRegistered
}
r.commands[name] = function
return nil
}
//RegisterVariable registers a variable
func (r *Registry) RegisterVariable(name string, value string) error {
name = "$" + name
r.mutex.Lock()
defer r.mutex.Unlock()
_, ok := r.commands[name]
if ok == true {
return ErrFunctionAlreadyRegistered
}
r.commands[name] = func(session io.Writer, args string) (int, error) {
return io.WriteString(session, value)
}
return nil
}