-
Notifications
You must be signed in to change notification settings - Fork 34
Programming Model
Although not required, we recommand you review AWS Lambda Developer Guide first.
This document explains how common programming patterns and core concepts apply when authoring Lambda functions in Go.
The handler is a function in your code, that Lambda invokes when executing your code.
func handle(evt json.RawMessage, ctx *runtime.Context) (interface{}, error) {
...
}
func init() {
runtime.HandleFunc(handle)
}
As the runtime mimics the standard Go
http
package interface, other approaches for creating a handler are possible. Refer to the API documentation for more information.
- Lambda uses
evt
parameter to pass in event data to the handler. - Lambda uses
ctx
parameter to provide runtime information to the handler. - The handler can either return a value or an error. What happens to the result depends on the invocation type:
- In a synchronous execution,
RequestResponse
type, Lambda returns the result, serialized in JSON, to the client. - In an asynchronous execution,
Event
type, Lambda discards the result of the function call.
- In a synchronous execution,
package main
import (
"encoding/json"
"fmt"
"github.com/eawsy/aws-lambda-go/service/lambda/runtime"
)
func handle(evt json.RawMessage, ctx *runtime.Context) (interface{}, error) {
var user map[string]string
json.Unmarshal(evt, &user)
message := fmt.Sprintf("Hello, %s %s!", user["FirstName"], user["LastName"])
return message, nil
}
func init() {
runtime.HandleFunc(handle)
}
func main() {}
{
"FirstName": "John",
"LastName": "Doe"
}
docker run --rm -v $GOPATH:/go -v $PWD:/tmp eawsy/aws-lambda-go
For step by step instructions on how to create a Lambda function using the console, see [Getting Started](Getting Started).
aws lambda create-function \
--function-name handler-go \
--runtime python2.7 --handler handler.handle --zip-file fileb://handler.zip \
--role arn:aws:iam::AWS_ACCOUNT_NUMBER:role/lambda_basic_execution
aws lambda invoke
--function-name handler-go \
--payload '{"FirstName": "John", "LastName": "Doe"}' output.txt
The context is an object containing runtime information, that Lambda passes as the second parameter of the handler when executing your code.
See also the API documentation.
-
RemainingTimeInMillis()
returns the remaining execution time, in milliseconds, until Lambda terminates the function. -
FunctionName
is the name of the Lambda function that is executing. -
FunctionVersion
is the version of the Lambda function that is executing. If an alias is used to invoke the function, then it will be the version the alias points to. -
InvokedFunctionARN
is the ARN used to invoke this function. It can be function ARN or alias ARN. An unqualified ARN executes the $LATEST version and aliases execute the function version it is pointing to. -
MemoryLimitInMB
is the memory limit, in MB, you configured for the Lambda function. -
AWSRequestID
is the AWS request ID associated with the request. This is the ID returned to the client. If Lambda retries the invocation (in case of execution failure), the AWS request ID remains the same. -
LogGroupName
is the name of the CloudWatch log group where you can find logs written by your Lambda function. -
LogStreamName
is the name of the CloudWatch log stream where you can find logs written by your Lambda function. The log stream may or may not change for each invocation of the Lambda function. -
Identity
is the information about the Amazon Cognito identity provider when invoked through the AWS Mobile SDK. -
ClientContext
is the information about the client application and device when invoked through the AWS Mobile SDK.
package main
import (
"encoding/json"
"log"
"time"
"github.com/eawsy/aws-lambda-go/service/lambda/runtime"
)
func handle(evt json.RawMessage, ctx *runtime.Context) (interface{}, error) {
log.Printf("Log stream name: %s", ctx.LogStreamName)
log.Printf("Log group name: %s", ctx.LogGroupName)
log.Printf("Request ID: %s", ctx.AWSRequestID)
log.Printf("Mem. limits(MB): %d", ctx.MemoryLimitInMB)
// Code will execute quickly, so we add a 1 second intentional delay so you
// can see that in time remaining value.
select {
case <-time.After(1 * time.Second):
log.Printf("Time remaining (MS): %d", ctx.RemainingTimeInMillis())
}
return nil, nil
}
func init() {
runtime.HandleFunc(handle)
}
func main() {}
docker run --rm -v $GOPATH:/go -v $PWD:/tmp eawsy/aws-lambda-go
For step by step instructions on how to create a Lambda function using the console, see [Getting Started](Getting Started).
aws lambda create-function \
--function-name context-go \
--runtime python2.7 --handler handler.handle --zip-file fileb://handler.zip \
--role arn:aws:iam::AWS_ACCOUNT_NUMBER:role/lambda_basic_execution
aws lambda invoke --function-name context-go output.txt
The handler can contain logging statements by using the standard Go log
package. The predefined standard logger
prints the timestamp and the AWS Request ID along with each logged message. Lambda writes these logs to CloudWatch.
Print[f|ln]
helper functions simply write a log message.
package main
import (
"encoding/json"
"log"
"github.com/eawsy/aws-lambda-go/service/lambda/runtime"
)
func handle(evt json.RawMessage, ctx *runtime.Context) (interface{}, error) {
log.Printf("Hello, %s!", "World")
return nil, nil
}
func init() {
runtime.HandleFunc(handle)
}
func main() {}
docker run --rm -v $GOPATH:/go -v $PWD:/tmp eawsy/aws-lambda-go
For step by step instructions on how to create a Lambda function using the console, see [Getting Started](Getting Started).
aws lambda create-function \
--function-name log-standard-go \
--runtime python2.7 --handler handler.handle --zip-file fileb://handler.zip \
--role arn:aws:iam::AWS_ACCOUNT_NUMBER:role/lambda_basic_execution
aws lambda invoke --function-name log-standard-go output.txt
Fatal[f|ln]
helper functions call os.Exit(1)
after writing the log message. It makes the Lambda execution fail with
the Process exited before completing request error message.
package main
import (
"encoding/json"
"log"
"github.com/eawsy/aws-lambda-go/service/lambda/runtime"
)
func handle(evt json.RawMessage, ctx *runtime.Context) (interface{}, error) {
log.Fatal("Whoops!")
return nil, nil
}
func init() {
runtime.HandleFunc(handle)
}
func main() {}
docker run --rm -v $GOPATH:/go -v $PWD:/tmp eawsy/aws-lambda-go
For step by step instructions on how to create a Lambda function using the console, see [Getting Started](Getting Started).
aws lambda create-function \
--function-name log-fatal-go \
--runtime python2.7 --handler handler.handle --zip-file fileb://handler.zip \
--role arn:aws:iam::AWS_ACCOUNT_NUMBER:role/lambda_basic_execution
aws lambda invoke --function-name log-fatal-go output.txt
Panic[f|ln]
helper functions call panic
after writing the log message. It makes the Lambda execution fail with the
given error message.
package main
import (
"encoding/json"
"log"
"github.com/eawsy/aws-lambda-go/service/lambda/runtime"
)
func handle(evt json.RawMessage, ctx *runtime.Context) (interface{}, error) {
log.Panic("Something bad happened.")
return nil, nil
}
func init() {
runtime.HandleFunc(handle)
}
func main() {}
docker run --rm -v $GOPATH:/go -v $PWD:/tmp eawsy/aws-lambda-go
For step by step instructions on how to create a Lambda function using the console, see [Getting Started](Getting Started).
aws lambda create-function \
--function-name log-panic-go \
--runtime python2.7 --handler handler.handle --zip-file fileb://handler.zip \
--role arn:aws:iam::AWS_ACCOUNT_NUMBER:role/lambda_basic_execution
aws lambda invoke --function-name log-panic-go output.txt
It's worth noting that the execution result stackTrace is not relevant in this non offcial runtime. To access the real stack trace, refer to the log output.
The handler can return a standard Go error
. Lambda recognizes the error and serializes its information into JSON and
returns it to the client.
package main
import (
"encoding/json"
"errors"
"github.com/eawsy/aws-lambda-go/service/lambda/runtime"
)
func handle(evt json.RawMessage, ctx *runtime.Context) (interface{}, error) {
return nil, errors.New("Oh, Snap!")
}
func init() {
runtime.HandleFunc(handle)
}
func main() {}
docker run --rm -v $GOPATH:/go -v $PWD:/tmp eawsy/aws-lambda-go
For step by step instructions on how to create a Lambda function using the console, see [Getting Started](Getting Started).
aws lambda create-function \
--function-name error-go \
--runtime python2.7 --handler handler.handle --zip-file fileb://handler.zip \
--role arn:aws:iam::AWS_ACCOUNT_NUMBER:role/lambda_basic_execution
aws lambda invoke --function-name error-go output.txt
Copyright 2016 Alsanium, SAS. or its affiliates. All rights reserved.
Source code licensed under the Apache License, Version 2.0.
Documentation licensed under the Creative Commons Attribution 4.0 International Public License.
[Getting Started](Getting Started)
- [Create](Getting Started#create-a-hello-world-lambda-function)
- [Invoke](Getting Started#invoke-the-lambda-function-manually)
- [Verify](Getting Started#verify-execution-results-and-logs)
[Programming Model](Programming Model)
- [Handler](Programming Model#handler)
- [Context](Programming Model#context)
- [Logging](Programming Model#logging)
- [Errors](Programming Model#errors)
[Deployment Package](Deployment Package)
- [Project](Deployment Package#project)
- [Package](Deployment Package#package)