DEV Community

JackTT
JackTT

Posted on

AWS Lambda with Go - How to Build, Deploy, and Invoke

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 with lambda.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)
Enter fullscreen mode Exit fullscreen mode
  • ctx: context for timeout, logs, request ID
  • TIn and TOut 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)
}
```
Enter fullscreen mode Exit fullscreen mode

2. Deployment methods

(a) Zip deployment

GOOS=linux GOARCH=amd64 go build -o bootstrap main.go
zip function.zip bootstrap
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"}`),
})
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Update function code (ZIP deployment)

aws lambda update-function-code \
  --function-name MyFunction \
  --zip-file fileb://function.zip
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)