DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

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πŸ₯Ί

Top comments (0)