Build, Deploy, and Invoke AWS Lambda Functions in Golang
1. Initialize Lambda main function & handler in Go
- Go Lambda starts from the
main()
function, usually withlambda.Start(handler)
. - Handler function signatures:
func ()
func () error
func () (TOut, error)
func (TIn) error
func (TIn) (TOut, error)
func (context.Context) error
func (context.Context) (TOut, error)
func (context.Context, TIn) error
func (context.Context, TIn) (TOut, error)
-
ctx
: context for timeout, logs, request ID -
TIn
andTOut
represent types that can be Unmarshal JSON.
Example:
```go
package main
import (
"context"
"github.com/aws/aws-lambda-go/lambda"
)
type MyEvent struct {
Name string `json:"name"`
}
func handler(ctx context.Context, e MyEvent) (string, error) {
return "Hello " + e.Name, nil
}
func main() {
lambda.Start(handler)
}
```
2. Deployment methods
(a) Zip deployment
GOOS=linux GOARCH=amd64 go build -o bootstrap main.go
zip function.zip bootstrap
Upload function.zip
to Lambda.
(b) Docker container deployment
Dockerfile example:
FROM public.ecr.aws/lambda/go:1
COPY main ${LAMBDA_TASK_ROOT}
CMD ["main"]
Push the image to ECR and deploy.
3. Invocation methods
AWS CLI
aws lambda invoke --function-name MyFunction --payload '{"name":"Jack"}' response.json
cat response.json
Go SDK (aws-sdk-go-v2)
client := lambda.NewFromConfig(cfg)
resp, err := client.Invoke(context.TODO(), &lambda.InvokeInput{
FunctionName: aws.String("MyFunction"),
Payload: []byte(`{"name":"Jack"}`),
})
4. Create & Update Lambda Function via AWS CLI
Create function (ZIP deployment)
aws lambda create-function \
--function-name MyFunction \
--runtime go1.x \
--role arn:aws:iam::<account-id>:role/<lambda-execution-role> \
--handler bootstrap \
--zip-file fileb://function.zip
Update function code (ZIP deployment)
aws lambda update-function-code \
--function-name MyFunction \
--zip-file fileb://function.zip
Top comments (0)