

AWS SDK for Go V1 has reached end-of-support. We recommend that you migrate to [AWS SDK for Go V2](https://docs.aws.amazon.com/sdk-for-go/v2/developer-guide/). For additional details and information on how to migrate, please refer to this [announcement](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-go-v1-on-july-31-2025/).

# AWS Lambda Examples Using the AWS SDK for Go
<a name="using-lambda-with-go-sdk"></a>

AWS Lambda (Lambda) is a zero-administration compute platform for backend web developers that runs your code for you in the AWS Cloud, and provides you with a fine-grained pricing structure. You can use the following examples to access AWS Lambda (Lambda) using the AWS SDK for Go. For more information about Lambda, see the [Lambda documentation](https://aws.amazon.com/documentation/lambda/).

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/lambda) repository on GitHub.

**Topics**
+ [Displaying Information about All Lambda Functions](lambda-go-example-show-functions.md)
+ [Creating a Lambda Function](lambda-go-example-create-function.md)
+ [Running a Lambda Function](lambda-go-example-run-function.md)
+ [Configuring a Lambda Function to Receive Notifications](lambda-go-example-configure-function-for-notification.md)

# Displaying Information about All Lambda Functions
<a name="lambda-go-example-show-functions"></a>

First import the packages we use in this example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/lambda"

    "fmt"
    "os"
)
```

Next, create the session and Lambda client.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

svc := lambda.New(sess, &aws.Config{Region: aws.String("us-west-2")})
```

Next, call `ListFunctions` and exit if there is an error.

```
result, err := svc.ListFunctions(nil)
if err != nil {
    fmt.Println("Cannot list functions")
    os.Exit(0)
}
```

Finally, display the names and descriptions of the Lambda functions.

```
fmt.Println("Functions:")

for _, f := range result.Functions {
    fmt.Println("Name:        " + aws.StringValue(f.FunctionName))
    fmt.Println("Description: " + aws.StringValue(f.Description))
    fmt.Println("")
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/lambda/aws-go-sdk-lambda-example-show-functions.go) on GitHub.

# Creating a Lambda Function
<a name="lambda-go-example-create-function"></a>

The following example creates the Lambda function `functionName` in the `us-west-2` region using the following values:
+ Role ARN: `resourceArn`. In most cases, you need to attach only the `AWSLambdaExecute` managed policy to the policy for this role.
+ Function entry point: `handler` 
+ Runtime: `runtime` 
+ Zip file: `zipFileName` \$1 `.zip` 
+ Bucket: `amzn-s3-demo-bucket` 
+ Key: `zipFileName` 

The first step is to import the packages we use in the example.

```
import (
    "flag"
    "fmt"
    "io/ioutil"

    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/lambda"
)
```

Get the zip file name, bucket name, function name, handler, ARN, and runtime values from the command line. If any are missing, print and error message and quit.

```
zipFile := flag.String("z", "", "The name of the ZIP file, without the .zip extension.")
bucket := flag.String("b", "", "the name of bucket to which the ZIP file is uploaded.")
function := flag.String("f", "", "The name of the Lambda function.")
handler := flag.String("h", "main", "The name of the package.class handling the call.")
roleARN := flag.String("a", "", "The ARN of the role that calls the function.")
runtime := flag.String("r", "go1.x", "The runtime for the function.")

flag.Parse()

if *zipFile == "" || *bucket == "" || *function == "" || *handler == "" || *roleARN == "" || *runtime == "" {
    fmt.Println("You must supply a zip file name, bucket name, function name, handler (package) name, role ARN, and runtime value.")
    return
}
```

Create the session and Lambda client and get the contents of the zip file. If you cannot read the zip file contents, print an error message and quit.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Next, create the structures for the input argument to the `CreateFunction` function.

```
createCode := &lambda.FunctionCode{
    //      S3Bucket:        bucket,
    //      S3Key:           zipFile,
    //      S3ObjectVersion: aws.String("1"),
    ZipFile: contents,
}

createArgs := &lambda.CreateFunctionInput{
    Code:         createCode,
    FunctionName: function,
    Handler:      handler,
    Role:         role,
    Runtime:      runtime,
}
```

Finally, call `CreateFunction` and display a message with the result of the call.

```
result, err := svc.CreateFunction(createArgs)
```

# Running a Lambda Function
<a name="lambda-go-example-run-function"></a>

The following example runs the Lambda function `MyGetitemsFunction` in the `us-west-2` region. This Node.js function returns a list of items from a database. The input JSON looks like the following.

```
{
   "SortBy": "name|time",
   "SortOrder": "ascending|descending",
   "Number": 50
}
```

Where:
+  `SortBy` is the criteria for sorting the results. Our example uses `time`, which means the returned items are sorted in the order in which they were added to the database.
+  `SortOrder` is the order of sorting. Our example uses `descending`, which means the most-recent item is last in the list.
+  `Number` is the maximum number of items to retrieve (the default is 50). Our example uses `10`, which means get the 10 most-recent items.

The output JSON looks like the following when the function succeeds and two items are returned.

```
{
   "statusCode": 200,
   "body": {
      "result": "success",
      "error": ""
      "data": [
         {
            "item": "item1"
         },
         {
            "item": "item2"
         }
      ]
   }
}
```

Where:
+  `statusCode`– An HTTP status code; `200` means the call was successful.
+  `body`– The body of the returned JSON.
+  `result`– The result of the call, either `success` or `failure`.
+  `error`– An error message if `result` is `failure`; otherwise, an empty string.
+  `data`– The returned results if `result` is `success`; otherwise, nil.
+  `item`– An item from the list of results.

The first step is to import the packages we use.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/lambda"
    
    "encoding/json"
    "fmt"
    "os"
    "strconv"
)
```

Next create session and Lambda client we use to invoke the Lambda function.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

client := lambda.New(sess, &aws.Config{Region: aws.String("us-west-2")})
```

Next, create the request and payload, and call `MyGetItemsFunction`. If there is an error, display a message and quit.

```
request := getItemsRequest{"time", "descending", 10}

payload, err := json.Marshal(request)
if err != nil {
    fmt.Println("Error marshalling MyGetItemsFunction request")
    os.Exit(0)
}

result, err := client.Invoke(&lambda.InvokeInput{FunctionName: aws.String("MyGetItemsFunction"), Payload: payload})
if err != nil {
    fmt.Println("Error calling MyGetItemsFunction")
    os.Exit(0)
}
```

Finally, parse the response, and if successful, print out the items.

```
var resp getItemsResponse

err = json.Unmarshal(result.Payload, &resp)
if err != nil {
    fmt.Println("Error unmarshalling MyGetItemsFunction response")
    os.Exit(0)
}

// If the status code is NOT 200, the call failed
if resp.StatusCode != 200 {
    fmt.Println("Error getting items, StatusCode: " + strconv.Itoa(resp.StatusCode))
    os.Exit(0)
}

// If the result is failure, we got an error
if resp.Body.Result == "failure" {
    fmt.Println("Failed to get items")
    os.Exit(0)
}

// Print out items
if len(resp.Body.Data) > 0 {
    for i := range resp.Body.Data {
        fmt.Println(resp.Body.Data[i].Item)
    }
} else {
    fmt.Println("There were no items")
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/lambda/aws-go-sdk-lambda-example-run-function.go) on GitHub.

**Note**  
The [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/lambda/aws-go-sdk-lambda-example-run-function.go) includes the structures for marshaling the JSON request and unmarshaling the JSON response.

# Configuring a Lambda Function to Receive Notifications
<a name="lambda-go-example-configure-function-for-notification"></a>

The following example configures the Lambda function `functionName` to accept notifications from the resource with the ARN `sourceArn`.

Import the packages we use.

```
import (
    "flag"
    "fmt"
    "os"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/lambda"
)
```

Get the name of the function and ARN of the entity invoking the function. If either is missing, print an error message and quit.

```
functionPtr := flag.String("f", "", "The name of the Lambda function")
sourcePtr := flag.String("a", "", "The ARN of the entity invoking the function")
flag.Parse()

if *functionPtr == "" || *sourcePtr == "" {
    fmt.Println("You must supply the name of the function and of the entity invoking the function")
    flag.PrintDefaults()
    os.Exit(1)
}
```

Create the session and Lambda client.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

svc := lambda.New(sess)
```

Create the structure for the input argument to the `AddPermission` function.

```
permArgs := &lambda.AddPermissionInput{
    Action:       aws.String("lambda:InvokeFunction"),
    FunctionName: functionPtr,
    Principal:    aws.String("s3.amazonaws.com"),
    SourceArn:    sourcePtr,
    StatementId:  aws.String("lambda_s3_notification"),
}
```

Finally, call `AddPermission` and display a message with the result of the call.

```
result, err := svc.AddPermission(permArgs)
if err != nil {
    fmt.Println("Cannot configure function for notifications")
    os.Exit(0)
}

fmt.Println(result)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/lambda/aws-go-sdk-lambda-example-configure-function-for-notification.go) on GitHub.