The Art of Crafting a Powerful Go Lambda Function from Scratch
Tags: goprogramming, serverlesscomputing, awslambda, clouddevelopment
Published: 2023-11-22 12:38:40

I'll guide you through the quickest and simplest path to creating a fully functional Go serverless application. You'll learn how to build an AWS Lambda function from scratch, unlocking the power of serverless computing without the complexity. 

Before, be aware:
* Api Gateway has a limit of 30s per request
* If your built code takes more than 10mb you probably should use containers for deploy.

![Go Gopher kart race](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bi651hg2pidejf9qt15k.png)

## Preparing the code for deploy
Before we dive into creating our AWS Lambda Function, let's prepare our code so AWS can easily find and run our Handler function.

Here is an example of code, i recommend try to deploy this one first and then your own codes:
```
package main

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

type MyEvent struct {
	Name string `json:"What is your name?"`
	Age  int    `json:"How old are you?"`
}

type MyResponse struct {
	Message string `json:"Answer"`
}

func HandleLambdaEvent(event *MyEvent) (*MyResponse, error) {
	if event == nil {
		return nil, fmt.Errorf("received nil event")
	}
	return &MyResponse{Message: fmt.Sprintf("%s is %d years old!", event.Name, event.Age)}, nil
}

func main() {
	lambda.Start(HandleLambdaEvent)
}
```

Save this code in a folder named lambda-test as main.go and execute the following commands:
```$ go mod init lambda-test```
```$ go mod tidy```

These commands will install all the required packages. While not necessary for building and deploying, they can be useful for experimenting with and exploring the code.

## Building
After configuring our code with the `HandleLambdaEvent` and `lambda.Start`, the next step is to focus on building the project. To streamline this process, I recommend using a Makefile:

Create a file named Makefile in the project's root directory.

```
build:
	GOOS=linux GOARCH=amd64 go build -o main  *.go
	zip -r main.zip main
	rm main
```

Within the Makefile, you can define the build process for your code, including zipping the necessary files. Don't forget to include a line to remove the build results, leaving only the zip file required for deployment.

Ensure you've included to the zip command any additional files your code requires, such as a .env file, in the project directory before proceeding with the Makefile setup. We are going to use the zipped code later.

It's important to note that you should build for the Lambda machine's architecture, which is why we've set `GOARCH=amd64` in the Makefile.

`$ make build`.

## Creating Lambda

In the AWS Console, navigate to the Lambda page and click on `Create Function`.

![Aws Console Create Function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1pgbsmyxq6xeogvspgy.png)

Enter the name for your Lambda function, and then change the runtime from `Node` to `Go 1.x` and Create the function

![Renaming Handler](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ku9hqn8vfcue0q6x95y4.png)

Now go to runtime settings in the `lambda-test` panel and rename the handler to `main`.

## Sending our code to the Lambda.

![Upload](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hyrtit55iiuuwgkh92rx.png)

Select `Upload from` then .zip and choose the zipfile inside your project. (The one generated from `$ make build`).

If your built code is bigger than `10mb` you should use S3.

Go to the test section:

![Testing Lambda on AWS Console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/71xlah11rwsdrdq95m0r.png)

Now we should test our lambda, set the Test Json to:

```
{
    "What is your name?": "Jim",
    "How old are you?": 33
}
```
If you've followed the steps correctly, you should receive:

```
{
  "Answer": "Jim is 33 years old!"
}
```

## Exposing to the internet 

Proceed to the AWS Console, navigate to the API Gateway homepage, and click on 'Create API'.


![Create API Page on AWS Console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h0ih52mjny6748ke3676.png)

Click on the `Build` button inside `REST API`

![Api gateway api config](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ym2utzouv3y6tmzn9x7y.png)

Add an name for your api gateway and create

![Api Gateway dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m7lpkr2msxlmbxy8ui28.png)

Click on `Create Method`.

![Creating api method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ksjo7pch8hlfo7gf4zb.png)

Here select POST and select your lambda function.

Now we need to deploy our API, for that click on deploy and if necessary create a new stage.

![Creating stage on aws](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7kci6itlywgicilxvdvk.png)

Now copy the invoke URL displayed on API Gateway and enjoy your new API!

![Api testing on insomnia](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lk1qvlkesyx9hx7rewet.png)

## Wrapping it Up

Congratulations on navigating the intricacies of creating a fully functional Go serverless application on AWS Lambda! 🚀 You've learned how to build a Lambda function from scratch, unlocking the power of serverless computing without the headaches of complexity.

Now, armed with your newfound knowledge, you're ready to explore and expand your serverless capabilities with Go. Remember, the world of serverless computing is vast, and you've just scratched the surface. Keep experimenting, building, and pushing the boundaries of what you can achieve with Go and serverless architecture.

Happy coding, and may your serverless journeys be filled with success and innovation! 🎉