Hooks
Hook is a generic concept that indicates the action that accompanies an event when it is triggered.
Hertz provides a global Hook for injecting your processing logic on the server-side after triggering startup and before exiting.
StartHook
StartHook
is a function to be called after the server-side has triggered a start, represented in Hertz by the type CtxErrCallback
. Hertz uses the OnRun
property to store the StartHook
list.
Hook functions get triggered sequentially after triggering the startup. Once the call is completed, Hertz will officially start listening on the port, or terminate the service immediately if any error occurs.
Function signatures:
Sample Code:
Note: After triggering startup, The logs of the three StartHook
functions will be printed in the terminal in order.
ShutdownHook
ShutdownHook
is a function to be called before the server-side exiting, represented in Hertz by the type CtxCallback
. Hertz uses the OnShutdown
property to store the ShutdownHook
list.
Hook functions get triggered simultaneously before the server-side exiting. The user can configure the max expiration time by server.WithExitWaitTime
, the default is 5 seconds, and once timeout, the server is terminated.
The ShutdownHook
call process is essentially a part of the Hertz Graceful Shutdown.
Function signatures:
Sample Code1:
Note: Before exiting, the logs of the three ShutdownHook
functions will be printed in the terminal disorderly.
Sample Code2:
Note: When terminating the service, the timeout log is printed because the hook function took more than 2 seconds to execute.
OnAccept
OnAccept
is a function to be called after connection accepted
but before adding it to epoll.
Sample Code:
Note: After sending the request, OnAccept
function will be printed in the terminal.
main.go:32: [Info] run the onAccept
main.go:38: [Info] pong
OnConnect
OnConnect
is a function to be called after adding it to epoll. The difference is that onConnect can get data but OnAccept cannot.
Sample Code:
Note: After sending the request, OnConnect
function will be printed in the terminal.
main.go:19: [Info] onconnect
main.go:20: [Info] [71 69 84]