-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrouter.go
More file actions
50 lines (42 loc) · 942 Bytes
/
router.go
File metadata and controls
50 lines (42 loc) · 942 Bytes
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
package pubsubrouter
import (
"runtime/debug"
"sync"
"github.com/google/martian/log"
"github.com/sofyan48/pubsub-router/pkg/client"
)
type Router struct {
sync.Mutex
handlers map[string]Handler
}
func NewRouter() *Router {
return &Router{
handlers: map[string]Handler{},
}
}
func (r *Router) Handle(routes string, h Handler) *Router {
r.Lock()
defer r.Unlock()
r.handlers[routes] = h
return r
}
func (r *Router) HandleMessage(m *Message) error {
path := m.Payload.Attributes[client.MessageAttributeNameRoute]
defer func() {
if err := recover(); err != nil {
log.Errorf("panic recovered: %v | stack : %v", err, string(debug.Stack()))
}
}()
h, okRoute := r.handlers[path]
if okRoute {
err := h.HandleMessage(m)
if err != nil {
m.Payload.Nack()
return err
}
m.Payload.Ack()
}
// if you need reporting please contrib this error handling
// return errors.New("Route Not Any Match")
return nil
}