/
dispatcher.go
59 lines (52 loc) · 1.14 KB
/
dispatcher.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
package lib
import (
"github.com/botyard/botyard/lib/log"
"github.com/botyard/botyard/lib/message"
kitlog "github.com/go-kit/kit/log"
"golang.org/x/net/context"
)
type Dispatcher struct {
ctx context.Context
loader *Loader
msgChannel chan *message.Message
logger kitlog.Logger
}
func NewDispatcher(ctx context.Context,
msgChannel chan *message.Message, loader *Loader) *Dispatcher {
d := &Dispatcher{
ctx: ctx,
loader: loader,
msgChannel: msgChannel,
logger: kitlog.NewContext(log.Logger).With("m", "dispatcher"),
}
go d.dispatch()
return d
}
func (d *Dispatcher) dispatch() {
for {
select {
case m := <-d.msgChannel:
for _, c := range d.loader.Commands {
req, ok := c.Match(m.Body)
if ok {
resp, err := c.Endpoint()(d.ctx, req)
if err != nil {
d.logger.Log("err", err)
continue
}
reply, err := c.Response(resp)
if err != nil {
d.logger.Log("err", err)
continue
}
reply.Address = m.Address //TODO:
gw, ok := d.loader.Gateways[m.Address.GatewayID]
if !ok {
continue
}
gw.SendMessage(reply)
}
}
}
}
}