20
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Go言語のAWS Lambdaから別Lambdaを呼び出そう

Last updated at Posted at 2018-05-09

AWS LambdaをGo言語で書いて、別Lambdaを呼び出したりしたのでメモを残す。
誰かのお役に立てば。

1. 別のLambda Functionを呼び出す

package main

import l "github.com/aws/aws-lambda-go/lambda"
import "github.com/aws/aws-sdk-go/service/lambda"
import "github.com/aws/aws-sdk-go/aws"
import "github.com/aws/aws-sdk-go/aws/session"
import "fmt"
import "encoding/json"

// これはLambda関数の完了で返すための構造体定義
type Response struct {
    Message string `json:"message"`
    Ok      bool   `json:"ok"`
}

// 別のLambdaに渡すための構造体定義
type Event struct {
    Id   int    `json:"id"`
    Name string `json:"name"`
}

func Handler() (Response, error) {
    // 呼び出したLambdaに渡すデータ
    payload := Event{
        Id:   1,
        Name: "yukpiz",
    }
    jsonBytes, _ := json.Marshal(payload)

    // このlambdaはaws/aws-lambda-go/lambdaではなく、
    // aws/aws-sdk-go-aws/service/lambdaなので注意
    svc := lambda.New(session.New())

    input := &lambda.InvokeInput{
        FunctionName:   aws.String("arn:aws:lambda:ap-northeast-1:xxxxxxxxxx:function:{function_name}"),
        Payload:        jsonBytes,
        InvocationType: aws.String("Event"),
    }

    resp, _ := svc.Invoke(input)
    fmt.Println(resp)

    return Response{
        Message: "success",
        Ok:      true,
    }, nil
}

func main() {
    l.Start(Handler)
}

InvocationTypeはLambdaの呼び出しタイプ。EventとRequestResponseが選べるやつ。
[呼び出しタイプ - AWS Lambda]
https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/java-invocation-options.html

InvokeInput構造体はその他のいくつかのオプションがある。
[lambda - Amazon Web Services - Go SDK]
https://docs.aws.amazon.com/sdk-for-go/api/service/lambda/#InvokeInput

2. HandlerでEventを受け取る

呼び出される側のLambda関数では、呼び出し元から渡された構造体を受け取る必要がある。

package main

import l "github.com/aws/aws-lambda-go/lambda"
import "fmt"

// 呼び出し元のLambdaから受け取るための構造体定義
type Event struct {
    Id   int    `json:"id"`
    Name string `json:"name"`
}

func Handler(event Event) (Response, error) {
    fmt.Println(event) //{1 yukpiz}
    return Response{
        Message: "success",
        Ok:      true,
    }, nil
}

func main() {
    l.Start(Handler)
}

このあたりも参考に
[Lambda Function Handler(Go) - AWS Lambda]
https://docs.aws.amazon.com/lambda/latest/dg/go-programming-model-handler-types.html

負荷分散の為に、別Lambdaを呼び出す構造は割とスタンダードのよう。
Step Functionsで負荷分散の並列処理ができるようになってほしい。

20
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?