This repository was archived by the owner on Jul 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest-handlers.go
More file actions
68 lines (51 loc) · 1.47 KB
/
request-handlers.go
File metadata and controls
68 lines (51 loc) · 1.47 KB
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
package gosrv
import (
"strings"
"cyberpull.com/gotk/v2/errors"
)
type RequestHandler func(ctx Context) Output
type RequestHandlerCollection interface {
On(method, channel string, handler RequestHandler) (err error)
}
type pRequestHandlerCollection struct {
handlers map[string]RequestHandler
}
func (s *pRequestHandlerCollection) key(method, channel string) string {
method = strings.ToUpper(method)
return method + "::" + channel
}
func (s *pRequestHandlerCollection) Has(method, channel string) bool {
key := s.key(method, channel)
_, ok := s.handlers[key]
return ok
}
func (s *pRequestHandlerCollection) Get(method, channel string) (handler RequestHandler, err error) {
key := s.key(method, channel)
handler, ok := s.handlers[key]
if !ok {
err = errors.Newf(`No action found for "%s" -> "%s"`, 400, method, channel)
return
}
return
}
func (s *pRequestHandlerCollection) On(method, channel string, handler RequestHandler) (err error) {
if s.Has(method, channel) {
err = errors.Newf(`Action already exists for "%s" -> "%s"`, 500, method, channel)
return
}
key := s.key(method, channel)
s.handlers[key] = handler
return
}
func (s *pRequestHandlerCollection) Off(method, channel string) {
if s.Has(method, channel) {
key := s.key(method, channel)
delete(s.handlers, key)
}
}
// ============================
func newRequestHandlerCollection() *pRequestHandlerCollection {
return &pRequestHandlerCollection{
handlers: make(map[string]RequestHandler),
}
}