Go の AWS Lambda Context オブジェクト
Lambda で関数が実行されると、コンテキストオブジェクトはハンドラに渡されます。このオブジェクトは、呼び出し、関数、および実行関数に関する情報を含むメソッドおよびプロパティを提供します。
Lambda コンテキストライブラリは、次のグローバル変数、メソッド、およびプロパティを提供します。
グローバル変数
-
FunctionName
– The name of the Lambda function. -
FunctionVersion
– The version of the function. -
MemoryLimitInMB
– The amount of memory configured on the function. -
LogGroupName
– The log group for the function. -
LogStreamName
– The log stream for the function instance.
コンテキストメソッド
-
Deadline
– Returns the date that the execution times out, in Unix time milliseconds.
コンテキストプロパティ
-
InvokedFunctionArn
– The Amazon Resource Name (ARN) used to invoke the function. Indicates if the invoker specified a version number or alias. -
AwsRequestID
– The identifier of the invocation request. -
Identity
– (mobile apps) Information about the Amazon Cognito identity that authorized the request. -
ClientContext
– (mobile apps) Client context provided to the Lambda invoker by the client application.
呼び出しコンテキスト情報へのアクセス
Lambda 関数には、環境と呼び出しリクエストに関するメタデータへのアクセスがあります。これには、パッケージのコンテキストでアクセスできます。ハンドラにはパラメータとして context.Context
が含まれている必要があり、Lambda は関数に関する情報をコンテキストの Value
プロパティに挿入します。context.Context
のコンテキストにアクセスするために、lambdacontext
ライブラリをインポートする必要があることに注意してください。
package main import ( "context" "log" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-lambda-go/lambdacontext" ) func CognitoHandler(ctx context.Context) { lc, _ := lambdacontext.FromContext(ctx) log.Print(lc.Identity.CognitoPoolID) } func main() { lambda.Start(CognitoHandler) }
上記の例では、lc
はコンテキストオブジェクトがキャプチャした情報を消費するために使用される変数であり、log.Print(lc.Identity.CognitoPoolID)
はその情報を印刷します (この場合は CognitoPoolID)。
関数の実行時間のモニタリング
次の例では、Lambda 関数を実行するときにかかる時間をモニタリングするためにコンテキストオブジェクトを使用する方法を紹介しています。これによって、予期されるパフォーマンスを分析し、必要な場合には関数コードを調整します。
package main import ( "context" "log" "time" "github.com/aws/aws-lambda-go/lambda" ) func LongRunningHandler(ctx context.Context) (string, error) { deadline, _ := ctx.Deadline() deadline = deadline.Add(-100 * time.Millisecond) timeoutChannel := time.After(time.Until(deadline)) for { select { case <- timeoutChannel: return "Finished before timing out.", nil default: log.Print("hello!") time.Sleep(50 * time.Millisecond) } } } func main() { lambda.Start(LongRunningHandler) }