-
Notifications
You must be signed in to change notification settings - Fork 0
/
context_named_handler.go
98 lines (88 loc) · 2.47 KB
/
context_named_handler.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package admin
type NamedContextHandler struct {
Name string
Handler func(ctx *Context)
}
type NamedContextHandlersRegistrator interface {
InheritsFrom(registrator ...NamedContextHandlersRegistrator)
Add(handler ...*NamedContextHandler)
Get(name string) *NamedContextHandler
Each(cb func(handler *NamedContextHandler) (err error), state ...map[string]*NamedContextHandler) (err error)
}
type NamedContextHandlersRegistry struct {
handlers []*NamedContextHandler
byName map[string]*NamedContextHandler
inheritsFrom []NamedContextHandlersRegistrator
}
func (this *NamedContextHandlersRegistry) InheritsFrom(registrator ...NamedContextHandlersRegistrator) {
this.inheritsFrom = append(this.inheritsFrom, registrator...)
}
func (this *NamedContextHandlersRegistry) Add(handler ...*NamedContextHandler) {
this.handlers = append(this.handlers, handler...)
if this.byName == nil {
this.byName = make(map[string]*NamedContextHandler, len(handler))
}
for _, s := range handler {
this.byName[s.Name] = s
}
}
func (this *NamedContextHandlersRegistry) Each(cb func(handler *NamedContextHandler) (err error), state ...map[string]*NamedContextHandler) (err error) {
var s map[string]*NamedContextHandler
for _, s = range state {
}
if s == nil {
s = map[string]*NamedContextHandler{}
}
if this.byName != nil {
var ok bool
for name, f := range this.byName {
if _, ok = s[name]; !ok {
s[name] = f
if err = cb(f); err == ErrStopIteration {
return nil
} else if err != nil {
return
}
}
}
}
for _, parent := range this.inheritsFrom {
if err = parent.Each(cb, s); err == ErrStopIteration {
return nil
} else if err != nil {
return
}
}
return nil
}
func (this *NamedContextHandlersRegistry) Get(name string) (f *NamedContextHandler) {
if this.byName != nil {
if f = this.byName[name]; f != nil {
return
}
}
for _, parent := range this.inheritsFrom {
if f = parent.Get(name); f != nil {
return
}
}
return
}
func GetNamedContextHandlers(this NamedContextHandlersRegistrator) (handlers []*NamedContextHandler, err error) {
ok := func(f *NamedContextHandler) bool {
return true
}
err = this.Each(func(f *NamedContextHandler) (err error) {
if ok(f) {
handlers = append(handlers, f)
}
return nil
})
return
}
func MustGetNamedContextHandlers(this NamedContextHandlersRegistrator) (handlers []*NamedContextHandler, err error) {
if handlers, err = GetNamedContextHandlers(this); err != nil {
panic(err)
}
return
}