DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

1

Go - API Gateway + Lambda in Go

Here is a sample that implements API with AWS API Gateway integrated Lambda in Go.

Specification

  • Endpoint: https://<API ID>.execute-api.ap-northeast-1.amazonaws.com/<stage>/<Resource>
  • Http Method: GET
  • Parameters:
{
    "text": "string"
}
Enter fullscreen mode Exit fullscreen mode

Lambda handler in Go

Define a struct that is used as arguments.

package main

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

// Ref: https://docs.aws.amazon.com/lambda/latest/dg/golang-handler.html

// Receive arguments as struct.
type Event struct {
    Text string `json:"text"`
}

func (e *Event) validate() bool {
    valid := true
    if e.Text == "" {
        valid = false
    }
    return valid
}

// Response
type Response struct {
    Message string `json:"message"`
}

// Lambda handler
func HandleRequest(ctx context.Context, event Event) (Response, error) {
    resp := Response{}

    if !event.validate() {
        return resp, errors.Errorf("need text.")
    }

    // Something to do you want here.
    resp.Message = "ok"

    return resp, nil
}

// Main
func main() {
    lambda.Start(HandleRequest)
}
Enter fullscreen mode Exit fullscreen mode

Integration Request - Mapping Templates

Add values to set to struct.
Here it has set text

#set($allParams = $input.params())
{
    "text": "$input.params('text')",
    "body-json" : $input.json('$'),
...
}
Enter fullscreen mode Exit fullscreen mode

Response

Here is a response.

{
    "message": "ok"
}
Enter fullscreen mode Exit fullscreen mode

I have to write codes more💪
I have to write English more than that🥺

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay