How to build AWS Lambda with Go example code: Post/Get/Put/Delete

How to build AWS Lambda with Go example code

To build an AWS Lambda function with Go, you will need to do the following:

1. Install the AWS SDK for Go by running go get -u github.com/aws/aws-sdk-go
2. Create a new Go file for your Lambda function, and import the necessary packages from the AWS SDK.
3. Define a function that will serve as the entry point for your Lambda function, and ensure it has the correct signature.
4. Build your Go code and create a deployment package (e.g. a ZIP file).
5. Use the AWS CLI or the AWS Lambda console to create or update your Lambda function, and provide the deployment package as the function code.

Here’s an example of a simple Lambda function written in Go:

package main

import (
"context"
"github.com/aws/aws-lambda-go/lambda"
)

func HandleRequest(ctx context.Context) (string, error) {
return "Hello, World!", nil
}

func main() {
lambda.Start(HandleRequest)
}

Note: you will also need to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Build Aws Lambda with Post Request using Go example code

Here’s an example of an AWS Lambda function written in Go that can handle a POST request:

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

type Request struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    var req Request
    json.Unmarshal([]byte(request.Body), &req)
    fmt.Printf("Received request: %+v\n", req)

    response := events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Hello, %s! Your age is %d", req.Name, req.Age),
        StatusCode: 200,
    }
    return response, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function parses the incoming JSON payload in the request body and Unmarshals the json data into struct Request.
It then creates a response in the form of events.APIGatewayProxyResponse which contains a message including the Name and Age field from the request body.
You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Build Aws Lambda with Get Request using Go example code

Here’s an example of an AWS Lambda function written in Go that can handle a GET request:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    queryParams := request.QueryStringParameters

    name, ok := queryParams["name"]
    if !ok {
        name = "World"
    }

    response := events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Hello, %s!", name),
        StatusCode: 200,
    }
    return response, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the value of the “name” query parameter from the request object and if it’s not present, it defaults to “World”. It then creates a response in the form of events.APIGatewayProxyResponse which contains a message using the name parameter.

You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Build Aws Lambda with Put Request using Go example code

Here’s an example of an AWS Lambda function written in Go that can handle a PUT request:

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

type Request struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    var req Request
    json.Unmarshal([]byte(request.Body), &req)
    fmt.Printf("Received request: %+v\n", req)

    response := events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Hello, %s! Your age is %d", req.Name, req.Age),
        StatusCode: 200,
    }
    return response, nil
}

func main() {
    lambda.Start(HandleRequest)
}

This example is similar to the previous POST request example. In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function parses the incoming JSON payload in the request body and Unmarshals the json data into struct Request.
It then creates a response in the form of events.APIGatewayProxyResponse which contains a message including the Name and Age field from the request body.
You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.
Please note that in a PUT request, it is a common practice to update the existing data instead of creating a new one. You can use DynamoDB or other data storage service to store and update the data.

Build Aws Lambda with Delete Request using Go example code

Here’s an example of an AWS Lambda function written in Go that can handle a DELETE request:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    pathParams := request.PathParameters

    id, ok := pathParams["id"]
    if !ok {
        return events.APIGatewayProxyResponse{
            Body:       "Missing id in path",
            StatusCode: 400,
        }, nil
    }

    // Delete the item with the given id from your data store
    err := deleteItem(id)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to delete item",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Item with id %s deleted", id),
        StatusCode: 200,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the value of the “id” path parameter from the request object and if it’s not present, returns a Bad Request error message . It then calls deleteItem function which deletes the item with the given id from your data store.
In the deleteItem function you can use DynamoDB or other data storage service to delete the data.
It then creates a response in the form of events.APIGatewayProxyResponse which contains a message about the deleted item.
You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.