SECRET OF CSS

Creating a GoLang Lambda With Serverless Framework | by Nic Jennings | Sep, 2022


A step-by-step guide for developers

Source

If you are a fan of GoLang like me and want to create your first Lambda, you may find that it can be challenging getting a step-by-step guide. This article will demonstrate how easy it is, especially when using the extremely handy Serverless Framework. This article will assume you have an AWS account and a basic understanding of setting up an IAM user with access tokens.

Open a terminal in the directory where you keep all your code. Mine is simply called Code. In the terminal, run:

mkdir GoServerlessLambda

Note: GoServerlessLambda is what I will call my directory feel free to name it after your project.

cd GoServerlessLambda

Now it’s time to set up the Go Project.

go mod init github.com/<username>/go-serverless-lambda

Finally, let’s open this in VS Code.

code .

Finally, create your main.go file and add the following content:

package mainimport "fmt"func main() {
fmt.Println("Hello world!")
}

In the terminal, run

go run .

We should see the following in your terminal

go run . Hello World!

First, we must set up our project to install the required node modules.

npm init

Follow through the steps. This will be required later. Now install the serverless framework globally:

npm install -g serverless

Finally, let’s get our serverless setup. Create a new file called serverless.yml and add the following contents:

I like to use .env to manage my environment variables, so let’s get that set up so we can utilise that in our project.

Next, let’s add the commands to build and deploy our Lambda. In package.json, add:

npm i cross-env env-cmd serverless-dotenv-plugin -D

Now add the following to serverless.yml. This will make variables from your environment available in Lambda. We will utilise this later.

...plugins:
- serverless-dotenv-plugin
useDotenv: true...

Now create your .env file and add the following values getting the tokens from your IAM user in AWS.

AWS_TOKEN={YOUR_AWS_TOKEN}
AWS_SECRET={YOUR_AWS_SECRET}
AWS_PROFILE={THE AWS PROFILE YOU WISH TO USE}
AWS_REGION={YOUR TARGET AWS REGION}

and let’s add some convenient scripts to manage our build and deployments:

"scripts": {
"setup:dev": "env-cmd -f .env cross-env-shell serverless config credentials --provider aws -o --key '$AWS_TOKEN' --secret '$AWS_SECRET' --profile '$AWS_PROFILE'",
"build": "env GOOS=linux GOARCH=amd64 go build -o bin/goserverlesslambda .",
"deploy:dev": "env-cmd -f .env cross-env-shell serverless deploy --stage development --aws-profile '$AWS_PROFILE' --region '$AWS_REGION'",
},

To break the above scripts down:

  • setup:dev configures the serverless framework with your AWS credentials using your environment variables
  • build compiles the Go Application into a binary which will run in the Lambda environment
  • deploy:dev deploys the Lambda to the development stage using your environment variables

Let’s set up our project credentials with this command:

npm run setup:dev

This should output the following:

goserverlesslambda@1.0.0 setup:dev, etc.

Perfect. Time to make we get the Go application ready.

First, we need to install the required packages:

go get github.com/aws/aws-lambda-go

Then in main.go, we update the file to match the following:

Time to build our Go Binary and deploy it. Run the following:

npm run build
npm run deploy:dev

This is what will result:

goserverlesslambda@1.0.0 deploy: dev, etc. deploying goserverlesslambda, etc.

Open the endpoint provided in the terminal output in Postman and send a POST request:

1*7vsPuaogke ZGbnI pHzA

Great, we now have a Lambda function we can deploy to AWS and trigger from Postman successfully.

Create a new file called .env.development and add the environment variable databaseConnection:

databaseConnection={USERNAME}:{PASSWORD}@tcp({HOST})/{DATABASE}

Create a new directory called config and create a file called setup.go. Install the go-sql-driver package:

go get github.com/go-sql-driver/mysql

and add the following to the file:

In your main.go file add the following under the imports:

...var SetupError errorvar dbCon stringfunc init() {
dbCon = os.Getenv("dbCon")
SetupError = config.ConnectToDb(dbCon)
}
...

We must create the database connection outside of the handler, which is why we are doing it within an init function. It means the connection will be reused if a Lambda is retriggered before its instance is closed and also ensures we are not creating hundreds of unnecessary connections for every invocation.

Update the HandleRequest function to match the below:

Build and deploy your Lambda again:

npm run build
npm run deploy:dev

If everything is working as expected, we should again get the following:

1*7vsPuaogke ZGbnI pHzA

If the database connection has failed, then you will get the following response:

1*H6JP7jtDPLBRmE3U Qa5Xw

If you wish for the Lambda to be called from anywhere, we will need to update the GenerateResponse function as follows:

If you want to use this setup to deploy a production Lambda, then I recommend adding the following to package.json:

"deploy:prod": "env-cmd -f .env cross-env-shell serverless deploy --stage production  --aws-profile '$AWS_PROFILE' --region '$AWS_REGION'"

Adding a .env.production file for your databaseConnection (this will automatically be used with the production flag)

Custom Domain

If you want a custom domain, then using the serverless-domain-manager plugin is very easy. An example serverless.yml config would be:

${self:custom.enabled.${opt:stage}, self:custom.enabled.other} — As conditionals are not yet possible this will allow us to use the custom domain only on the Production stage built

Hopefully, you found this insightful and easy to follow. Good luck on your journey in creating your own GoLang Lambdas.



News Credit

%d bloggers like this: