LoginSignup
3

More than 1 year has passed since last update.

GoでLambda Function URLs ハンズオン

Last updated at Posted at 2022-05-12

はじめに

この記事はGoでLambda Function URLsをハンズオンしてみる内容となっています。
筆者がLambdaでGoを扱うこと自体が初めてだったため備忘録として簡単に環境構築からデプロイまでの手順も載せています。

環境

MacBook Air M1

ハンズオン

ランタイム Go1.xを選択後、
Lambdaの関数の作成画面で詳細設定を開き "関数URLを有効化"をチェックします。
(認証はパブリックな利用を想定してNONEを設定しました。)
function_urls.png

ランタイム設定のハンドラがhelloとなっているので適当な名前に変更します。
runtime_setting.png

環境構築

必要なパッケージのインストール

go get github.com/aws/aws-lambda-go

ソースコード

URLがAmazonのURLか判定して真偽値を返すだけのAPIです。

main.go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"regexp"
	"strings"

	"github.com/aws/aws-lambda-go/lambda"
)

type Payload struct {
	Body string `json:"body"`
}

type Request struct {
	URL string `json:"url"`
}

func HandleRequest(ctx context.Context, payload Payload) (bool, error) {
	var req Request
	err := json.NewDecoder(strings.NewReader(payload.Body)).Decode(&req)
	if err != nil {
		return false, fmt.Errorf("cannot decode payload: %v: %v", err, payload.Body)
	}

	isAmazonURL, err := regexp.MatchString(`^https://(www.)?amazon.(co.)?jp[\w!\?/\+\-_~=;\.,\*&@#\$%\(\)'\[\]]*`, req.URL)
	if err != nil {
		return false, err
	}

	return isAmazonURL, nil
}

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

*POSTのパラメータの取得方法がわからずハマりました。
参考: https://zenn.dev/mattn/articles/25aee329a54b38
*URLの正規表現
参考: https://qiita.com/str32/items/a692073af32757618042

デプロイ手順

ソースコードの用意ができたらビルドします。

GOARCH=amd64 GOOS=linux go build main.go

警告
M1 Macを使っている場合、GOARCH=amd64の指定が必要な点に注意してください。
参考:https://zenn.dev/mogamin/articles/lambda-go-with-apple-silicon

実行ファイルの圧縮をzipに圧縮します。

zip function.zip main.go

AWS Lambdaの画面に戻ってzipファイルのアップロードを行います。

実行

2つのパターンで動作確認

curl -X POST \
-H 'Content-Type: application/json' \
-d '{"url": "https://www.amazon.co.jp"}' \
'https://{id}.lambda-url.{region}.on.aws'

結果: true

curl -X POST \
-H 'Content-Type: application/json' \
-d '{"url": "https://example.com"}' \
'https://{id}.lambda-url.{region}.on.aws'

結果: false

最後に

次回はDynamoDBと連携させたい。

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
What you can do with signing up
3