This topic describes how to invoke lifecycle callbacks for function instances in the Go runtime environment.
Background information
Initializer callback
The initializer callback is invoked after the function instance is started but before the handler runs. FC ensures that the initializer callback can be successfully invoked at most once within the lifecycle of a function instance. For example, if the initializer callback fails, the system keeps retrying until the initializer callback is successfully invoked, and then runs your handler. Make sure that the initializer callback can be successfully invoked when you implement the initializer callback.
The initializer callback contains only the context input parameter and can be invoked in the same way as a handler.
function(ctx context.Context)
Use the initializer callback
To use the initializer callback, perform the following steps:
- Use
fc.RegistryInitializerFunction(Init)
in your application code to register an initializer callback.Sample code:
package main import ( "context" "log" "github.com/aliyun/fc-runtime-go-sdk/fc" ) var ( count int = 1 ) func Init(ctx context.Context) { count += 1000 } func main() { fc.RegisterInitializerFunction(Init) fc.Start(HandleRequest) } func HandleRequest() (int, error) { count += 1 log.Println("count: ", count) return count, nil }
The following content describes the code snippets in the sample code:
func Init(ctx context.Context)
: the initializer callback. Thectx context.Context
parameter specifies the runtime information for invoking a function in FC. For more information, see Context.- func main(): the entry point for running function code in FC. A Go application must contain the
main
function. You can addfc.Start(HandleRequest)
to your code to specify the method to execute the handler, and addfc.RegisterInitializerFunction(Init)
to register the initializer callback.Notice The preceding sample code applies only to an event handler. If you use an HTTP handler, replacefc.Start(HandleRequest)
in the sample code withfc.StartHttp(HandleRequest)
.
- Configure the initializer callback on the function configuration page of the Function Compute console, as shown in the following figure.
For more information, see Manage functions.
Sample code
Function Compute provides sample code for invoking the initializer callback. The sample code provides an example on how to use the initializer callback in the Go runtime environment to initialize a MySQL connection pool. In the sample code, the MySQL database is configured by using an environment variable of the function. For more information, see the s.yaml file. The initializer callback obtains the database configuration based on the environment variable, creates a MySQL connection pool, and then tests the connectivity.
For more information, see go-initializer-mysql.