Tuesday, September 6, 2022

How to Create Golang Lambda with Serverless Framework



 This is a beginner friendly step by step guide developers to create a Lambda function with Golang. We gonna use Serverless Framework. 

First, create the project directory and setting up the Go Project

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

Open in your favourite IDE, create the first file, main.go

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

then run it:

go run .

Next step, install and setting up the serverless framework:

npm init

npm install -g serverless

then, create a new file called serverless.yml:

service: goserverlesslambda
provider:
  name: aws
  runtime: go1.x
  region: {your_region}
package:
  patterns:
    - "!./**"
    - "./bin/**"
functions:
  goserverlesslambda:
    handler: bin/goserverlesslambda
    events:
      - http:
          path: /
          method: post
          cors: true
          private: false

To read and store apps configuration, we can use .env files. So, we've to install dotenv packages.

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

add in your package.yml files

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

then, edit the .env file:

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}

add the builder script like this:

"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'",
},

run the setup development:

npm run setup:dev

Begin Using Lambda

Install Go Lambda package:

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

on the main.go file add this script:

package main
import (
"context"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
func GenerateResponse(Body string, Code int) events.APIGatewayProxyResponse {
return events.APIGatewayProxyResponse{Body: Body, StatusCode: Code, }
}
func HandleRequest(_ context.Context, request events.LambdaFunctionURLRequest) (events.APIGatewayProxyResponse, error) {
return GenerateResponse("Hello World", 200), nil
}
func main() {
lambda.Start(HandleRequest)
}

save and build the go apps:

npm run build
npm run deploy:dev

0 comments:

Post a Comment