Customize Hook for Start/Shutdown of Server-side

Kitex provides a global Hook for injecting your processing logic on the server-side after triggering startup and before exiting.

Also, you can modify the main function to customize some processing logic before the server-side starts and after it exits (listening for port closures).

After the server-side start and before exit

Since the server-side logic after startup and before exit is processed inside the framework, users who want to customize the business logic need to use Hook for injection.

Inject StartHook triggered after startup

After triggering Server startup, the framework executes StartHooks and performs service registration. Note that since the Server starts asynchronously, the Hook is not guaranteed to be executed after the fully ready status of the server.

  • Usage

    import "github.com/cloudwego/kitex/server"
    
    server.RegisterStartHooks(yourStartHook)
    // support for injecting multiple Hooks
    // server.RegisterStartHooks(hook)
    

Inject ShutdownHook triggered before exit

After receiving an exit signal or when the user initiates a stop command, the framework executes ShutdownHooks first, followed by service deregistration (from the registry) and Shutdown of the service.

  • Usage
import "github.com/cloudwego/kitex/server"

server.RegisterShutdownHook(yourShundownHook)
// support inject multiple Hooks
// server.RegisterShutdownHook(hook)

Before the server-side startup and after exit

Customizing the logic before the server-side startup and after exit is easier for users. What you need to do is adding your processing logic before and after the execution of the Run() method in the main.go generated by the framework.

Note: The logic after Run() is not executed until the Server has finished exiting. If you want to execute your logic before Server exits, you should use ShutdownHook.

The following is an example of the main function generated by the framework, you may write your own logic in the position of comments.

func main() {
	svr := greetservice.NewServer(new(GreetServiceImpl))

  // yourLogicBeforeServerRun()

	err := svr.Run()

  // yourLogicAfterServerRun()

	if err != nil {
		log.Println(err.Error())
	}
}