-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheventhandler.go
81 lines (72 loc) · 1.99 KB
/
eventhandler.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
package singularity
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"sync"
)
//NewHandler1 ...
func NewHandler1() *EventAPIHandler {
eapih := &EventAPIHandler{}
eapih.handlers = make(map[string][]interface{})
return eapih
}
//EventAPIHandler ...
type EventAPIHandler struct {
sync.Mutex
handlerList
}
type handlerList struct {
sync.Mutex
handlers map[string][]interface{}
}
/*
One of the things that I'm thinking about, is requiting a naming convention for finding the `type`
*/
//WARNING, does not lock.
func (handler *EventAPIHandler) registerHandler(key string, function interface{}) error {
if function == nil {
return errors.New("Function can not be nul!")
}
rtype := fmt.Sprintf("%v", reflect.TypeOf(function))
if strings.HasPrefix(rtype, "func(") {
params := getFunctionParameters(rtype)
if len(params) != 2 && params[1] == "*singularity.SlackInstance" {
return errors.New("Function parameter missmatch!")
}
handler.handlerList.handlers[key] = append(handler.handlerList.handlers[key], function)
return nil
}
return nil
}
func (handler *EventAPIHandler) execute(key string, body []byte, instance *SlackInstance) (err error) {
handler.handlerList.Lock()
defer handler.handlerList.Unlock()
for _, function := range handler.handlerList.handlers[key] {
if func() bool {
defer func() {
if err1 := recover(); err1 != nil {
fmt.Printf("Recovered from Panic: %v\n", err1) //TODO Better Error Handling. //TODO Remove fmt.
if err != nil {
//err = err1?
}
}
}()
param0 := reflect.TypeOf(function).In(0) //Should be Param 0.
value := reflect.New(param0).Interface()
err = json.Unmarshal(body, &value)
if err != nil {
fmt.Printf("Error Executing: %v\n", err) //TODO Better Error Handling. //TODO Remove fmt.
fmt.Printf("Body: %v\n", string(body))
return false
}
reflect.ValueOf(function).Call([]reflect.Value{reflect.ValueOf(value).Elem(), reflect.ValueOf(instance)})
return false
}() {
break
}
}
return nil
}