Skip to content

Commit

Permalink
feat: 支持通过 server.Server.RegStopEvent() 函数注册服务器关闭事件
Browse files Browse the repository at this point in the history
  • Loading branch information
kercylan98 committed Jul 6, 2023
1 parent 7065448 commit 18b9598
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
14 changes: 14 additions & 0 deletions server/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

type StartBeforeEventHandle func(srv *Server)
type StartFinishEventHandle func(srv *Server)
type StopEventHandle func(srv *Server)
type ConnectionReceivePacketEventHandle func(srv *Server, conn *Conn, packet []byte)
type ConnectionReceiveWebsocketPacketEventHandle func(srv *Server, conn *Conn, packet []byte, messageType int)
type ConnectionOpenedEventHandle func(srv *Server, conn *Conn)
Expand All @@ -25,6 +26,7 @@ type event struct {
*Server
startBeforeEventHandles []StartBeforeEventHandle
startFinishEventHandles []StartFinishEventHandle
stopEventHandles []StopEventHandle
connectionReceivePacketEventHandles []ConnectionReceivePacketEventHandle
connectionReceiveWebsocketPacketEventHandles []ConnectionReceiveWebsocketPacketEventHandle
connectionOpenedEventHandles []ConnectionOpenedEventHandle
Expand All @@ -38,6 +40,18 @@ type event struct {
consoleCommandEventHandleInitOnce sync.Once
}

// RegStopEvent 服务器停止时将立即执行被注册的事件处理函数
func (slf *event) RegStopEvent(handle StopEventHandle) {
slf.stopEventHandles = append(slf.stopEventHandles, handle)
log.Info("Server", zap.String("RegEvent", runtimes.CurrentRunningFuncName()), zap.String("handle", reflect.TypeOf(handle).String()))
}

func (slf *event) OnStopEvent() {
for _, handle := range slf.stopEventHandles {
handle(slf.Server)
}
}

// RegConsoleCommandEvent 控制台收到指令时将立即执行被注册的事件处理函数
// - 默认将注册 "exit", "quit", "close", "shutdown", "EXIT", "QUIT", "CLOSE", "SHUTDOWN" 指令作为关闭服务器的指令
// - 可通过注册默认指令进行默认行为的覆盖
Expand Down
1 change: 1 addition & 0 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,7 @@ func (slf *Server) Ticker() *timer.Ticker {

// Shutdown 停止运行服务器
func (slf *Server) Shutdown(err error, stack ...string) {
slf.OnStopEvent()
defer func() {
if slf.multipleRuntimeErrorChan != nil {
slf.multipleRuntimeErrorChan <- err
Expand Down

0 comments on commit 18b9598

Please sign in to comment.