-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcompose.go
More file actions
65 lines (53 loc) · 1.63 KB
/
compose.go
File metadata and controls
65 lines (53 loc) · 1.63 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
package nsxbot
import (
"reflect"
"runtime"
"strings"
"github.com/nsxdevx/nsxbot/filter"
)
type FilterChain[T any] []filter.Filter[T]
func (f FilterChain[T]) debug() string {
var info string
for _, filter := range f {
info += strings.TrimPrefix(runtime.FuncForPC(reflect.ValueOf(filter).Pointer()).Name()+"->", "main.main.")
}
return info
}
type HandlersChain[T any] []HandlerFunc[T]
type HandlerFunc[T any] func(ctx *Context[T])
type Composer[T any] struct {
handlers HandlersChain[T]
filters FilterChain[T]
root *EventHandler[T]
}
// Use adds handlers to the Composer.
func (c *Composer[T]) Use(handlers ...HandlerFunc[T]) {
c.handlers = append(c.handlers, handlers...)
}
// Filit adds filters to the Composer.
func (c *Composer[T]) Filit(fillers ...filter.Filter[T]) {
c.filters = append(c.filters, fillers...)
}
// Compose creates a new Composer with the given filters.
func (c *Composer[T]) Compose(fillers ...filter.Filter[T]) *Composer[T] {
return &Composer[T]{
handlers: c.handlers,
root: c.root,
filters: c.combineFilters(fillers),
}
}
// Handle adds a handler to the Composer.
func (c *Composer[T]) Handle(handler HandlerFunc[T], filters ...filter.Filter[T]) {
handlerEnd := HandlerEnd[T]{
fillers: c.combineFilters(filters),
handlers: append(c.handlers, handler),
}
c.root.handlerEnds = append(c.root.handlerEnds, handlerEnd)
}
func (c *Composer[T]) combineFilters(filters FilterChain[T]) FilterChain[T] {
finalSize := len(c.filters) + len(filters)
mergedFilters := make(FilterChain[T], finalSize)
copy(mergedFilters, c.filters)
copy(mergedFilters[len(c.filters):], filters)
return mergedFilters
}