Deploying Serverless Go APIs with AWS SAM

Listen to this Post

Featured Image
AWS Serverless Application Model (SAM) simplifies deploying serverless applications on AWS. This guide demonstrates how to deploy a Go-based REST API using AWS Lambda and API Gateway with SAM.

You Should Know:

1. Prerequisites

  • AWS CLI configured (aws configure)
  • SAM CLI installed (brew install aws-sam-cli on macOS)
  • Go installed (sudo apt install golang on Linux)

2. Initialize a SAM Project

sam init --runtime go1.x --name go-serverless-api 
cd go-serverless-api 

3. Write a Lambda Function in Go

// main.go 
package main

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

func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { 
log.Println("Lambda invoked") 
return events.APIGatewayProxyResponse{ 
StatusCode: 200, 
Body: <code>{"message": "Hello, Serverless Go!"}</code>, 
}, nil 
}

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

4. Build & Deploy with SAM

GOOS=linux GOARCH=amd64 go build -o main 
sam build 
sam deploy --guided 

5. Test the API

curl -X GET https://YOUR_API_GATEWAY_URL 

6. Clean Up

sam delete 

What Undercode Say

AWS SAM streamlines serverless deployments, and Go’s efficiency makes it ideal for Lambda. Key takeaways:
– Use `sam init` for quick scaffolding.
– Cross-compile Go for Linux (GOOS=linux).
– Debug locally with sam local invoke.
– Monitor logs via AWS CloudWatch (aws logs tail /aws/lambda/FunctionName).

For further reading, check:

Expected Output:

{"message": "Hello, Serverless Go!"} 

References:

Reported By: Darryl Ruggles – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 Telegram