|
|
|
package lifetime
|
|
|
|
|
|
|
|
import (
|
|
|
|
"git.noahlan.cn/noahlan/nnet/connection"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
Handler func(conn *connection.Connection)
|
|
|
|
|
|
|
|
Lifetime interface {
|
|
|
|
OnClosed(h Handler)
|
|
|
|
OnOpen(h Handler)
|
|
|
|
}
|
|
|
|
|
|
|
|
Mgr struct {
|
|
|
|
onOpen []Handler
|
|
|
|
onClosed []Handler
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
func NewLifetime() *Mgr {
|
|
|
|
return &Mgr{
|
|
|
|
onOpen: make([]Handler, 0),
|
|
|
|
onClosed: make([]Handler, 0),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (lt *Mgr) OnClosed(h Handler) {
|
|
|
|
lt.onClosed = append(lt.onClosed, h)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (lt *Mgr) OnOpen(h Handler) {
|
|
|
|
lt.onOpen = append(lt.onOpen, h)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (lt *Mgr) Open(conn *connection.Connection) {
|
|
|
|
if len(lt.onOpen) <= 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, handler := range lt.onOpen {
|
|
|
|
handler(conn)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (lt *Mgr) Close(conn *connection.Connection) {
|
|
|
|
if len(lt.onClosed) <= 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, handler := range lt.onClosed {
|
|
|
|
handler(conn)
|
|
|
|
}
|
|
|
|
}
|