-
Notifications
You must be signed in to change notification settings - Fork 0
/
bootstrap.go
92 lines (76 loc) · 2.09 KB
/
bootstrap.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
package channel
import (
"context"
"net"
"reflect"
)
type Bootstrap interface {
Handler(handler Handler) Bootstrap
ChannelType(ch Channel) Bootstrap
Connect(localAddr net.Addr, remoteAddr net.Addr) Future
SetParams(key ParamKey, value interface{}) Bootstrap
Params() *Params
}
type BootstrapChannelPreInit interface {
BootstrapPreInit()
}
type BootstrapChannelPostInit interface {
BootstrapPostInit()
}
type DefaultBootstrap struct {
handler Handler
channelType reflect.Type
params Params
}
func (d *DefaultBootstrap) SetParams(key ParamKey, value interface{}) Bootstrap {
d.params.Store(key, value)
return d
}
func (d *DefaultBootstrap) Params() *Params {
return &d.params
}
func NewBootstrap() Bootstrap {
bootstrap := DefaultBootstrap{}
return &bootstrap
}
func (d *DefaultBootstrap) Handler(handler Handler) Bootstrap {
d.handler = handler
return d
}
func (d *DefaultBootstrap) ChannelType(ch Channel) Bootstrap {
d.channelType = reflect.ValueOf(ch).Elem().Type()
return d
}
func (d *DefaultBootstrap) Connect(localAddr net.Addr, remoteAddr net.Addr) Future {
channelType := reflect.New(d.channelType)
var channel = channelType.Interface().(Channel)
if preInit, ok := channel.(BootstrapChannelPreInit); ok {
preInit.BootstrapPreInit()
}
channel.setPipeline(_NewDefaultPipeline(channel))
cancel, cancelFunc := context.WithCancel(context.Background())
channel.setContext(cancel)
channel.setContextCancelFunc(cancelFunc)
d.Params().Range(func(k ParamKey, v interface{}) bool {
channel.SetParam(k, v)
return true
})
channel.Init()
if d.handler != nil {
channel.Pipeline().AddLast("ROOT", d.handler)
}
if preInit, ok := channel.(BootstrapChannelPostInit); ok {
preInit.BootstrapPostInit()
}
channel.setCloseFuture(channel.Pipeline().NewFuture())
channel.Pipeline().fireRegistered()
return channel.Connect(localAddr, remoteAddr)
}
func ValueSetFieldVal(target *reflect.Value, field string, val interface{}) bool {
if icc := target.Elem().FieldByName(field); icc.IsValid() && icc.CanSet() {
icc.Set(reflect.ValueOf(val))
return true
} else {
return false
}
}