Perform hook operations before the service starts

Updated at:

Use AddStartHook to run initialization logic before PAI-Rec starts accepting traffic. Register routes using HandleFunc or a custom controller that implements ControllerInterface.

Service initialization

Call AddStartHook to register a hook function with the PAI-Rec startup process. Each hook function must match the signature func() error. Hooks run in registration order before pairec.Run() starts the service.

pairec.AddStartHook(func() error {
    precall.RegisterRecall("LiveRoomRecall", recall.NewLiveRoomRecall())
    module.RegisterGenerateItemDataFunc(filter.GenerateExposureHistoryItemData)
    prank.SetBoostFunc(rank.BoostScore)
    return nil
})

Register multiple hooks by calling AddStartHook more than once. PAI-Rec calls them in the order they were registered.

Route configuration

PAI-Rec provides two ways to register routes, similar to standard Go HTTP handlers.

Option 1: HandleFunc

Pass a path and a handler function directly:

HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "success")
})

Option 2: Controller interface

Pass a path and a struct that implements ControllerInterface:

pairec.Route("/api/recommend", &web.RecommendController{})

To use a custom controller, implement the ControllerInterface interface:

type ControllerInterface interface {
    Process(http.ResponseWriter, *http.Request)
}

Process receives the standard Go http.ResponseWriter and *http.Request arguments. Write the HTTP response to w and read request details from r.

Complete example

This example combines hooks and routes in a main function:

func main() {
    pairec.AddStartHook(func() error {
        precall.RegisterRecall("LiveRoomRecall", recall.NewLiveRoomRecall())
        module.RegisterGenerateItemDataFunc(filter.GenerateExposureHistoryItemData)
        prank.SetBoostFunc(rank.BoostScore)
        return nil
    })

    pairec.Route("/api/rec/live_room_sync", &controller.LiveRoomSyncController{})
    pairec.Route("/api/rec/live_feed", &controller.LiveFeedController{})

    pairec.Run()
}