開発メモ

Go言語のLambda関数でAPI Gateway経由のJSON入力を処理するときのベース

February 16, 2019

Go言語で作ったLambda関数にて,API Gateway経由でJSON形式の入力を受け取る処理のベース部分の作りについてメモ

環境

  • MacOS Mojave
  • Go 1.11.5
  • Serverless Framework 1.37.1

プロジェクト作成

  • $GOHOME/src配下の任意フォルダで作業
    • helloworldの2つの関数(+API)を持つテンプレートが展開される
1$ sls create -t aws-go-dep -p <project-name>
  • serverless.ymlregionを追記 + helloのメソッドをPOSTに変更
 1provider:
 2  name: aws
 3  runtime: go1.x
 4  region: ap-northeast-1
 5...
 6functions:
 7  hello:
 8    handler: bin/hello
 9    events:
10      - http:
11          path: wake-up
12          method: post
13...

関数修正

  • hello側だけ修正してみる
    • リクエストのbodyにあるJSONを受け,得られた値を含む文字列を返すよう修正
 1package main
 2
 3import (
 4	"bytes"
 5	"context"
 6	"encoding/json"
 7	"fmt"
 8
 9	"github.com/aws/aws-lambda-go/events"
10	"github.com/aws/aws-lambda-go/lambda"
11)
12
13// Response is of type APIGatewayProxyResponse since we're leveraging the
14// AWS Lambda Proxy Request functionality (default behavior)
15//
16// https://serverless.com/framework/docs/providers/aws/events/apigateway/#lambda-proxy-integration
17type Response events.APIGatewayProxyResponse
18
19// InputBody is struct for body contents in api request
20type InputBody struct {
21	Test string `json:"test"`
22}
23
24// Handler is our lambda handler invoked by the `lambda.Start` function call
25func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (Response, error) {
26	var buf bytes.Buffer
27
28	// parse request.Body and create InputBody
29	var ib InputBody
30	var err = json.Unmarshal([]byte(request.Body), &ib)
31	if err != nil {
32		var em = "Error in parsing input body json"
33		fmt.Println(em)
34		resp := Response{
35			StatusCode: 400,
36			Body:       em,
37		}
38		return resp, err
39	}
40
41	// if parsed, create return message
42	var msg = "input is  " + ib.Test
43	body, err := json.Marshal(map[string]interface{}{
44		"message": msg,
45	})
46	if err != nil {
47		return Response{StatusCode: 404}, err
48	}
49	json.HTMLEscape(&buf, body)
50
51	resp := Response{
52		StatusCode:      200,
53		IsBase64Encoded: false,
54		Body:            buf.String(),
55		Headers: map[string]string{
56			"Content-Type":           "application/json",
57			"X-MyCompany-Func-Reply": "hello-handler",
58		},
59	}
60
61	return resp, nil
62}
63
64func main() {
65	lambda.Start(Handler)
66}
67
68

補足

  • Go言語でJSONを受けるには以下の手順が必要
  1. 想定入力のデータ構造をstructで定義
  2. 結果をstruct変数を用意
  3. request.Body配下の(JSON形式の)文字列をパース (Unmarshal)

デプロイ

  • 以下でデプロイ
    • make deploy = make + sls deploy
1$ cd <project-name>
2$ make deploy
  • 出力メッセージ中にあるURLにcurlやPostmanでアクセス

Tagged: #lambda #serverless framework #Go #API Gateway