-
Notifications
You must be signed in to change notification settings - Fork 5
/
engine.go
43 lines (35 loc) · 995 Bytes
/
engine.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
package znet
import (
"github.com/ebar-go/ego/utils/pool"
"github.com/ebar-go/znet/codec"
)
// Engine provide context/handler management
type Engine struct {
handleChains []HandleFunc // is a list of handlers
contextProvider pool.Provider[*Context] // is a pool for Context
}
func NewEngine() *Engine {
e := &Engine{}
e.contextProvider = pool.NewSyncPoolProvider[*Context](func() interface{} {
return &Context{engine: e}
})
return e
}
func (e *Engine) Use(handlers ...HandleFunc) {
e.handleChains = append(e.handleChains, handlers...)
}
// invoke process context handler chain
func (e *Engine) invoke(ctx *Context, index int8) {
if int(index) > len(e.handleChains)-1 {
return
}
e.handleChains[index](ctx)
}
// compute run invoke function with context
func (e *Engine) compute(conn *Connection, packet *codec.Packet) {
// acquire context from provider
ctx := e.contextProvider.Acquire()
ctx.reset(conn, packet)
defer e.contextProvider.Release(ctx)
e.invoke(ctx, 0)
}