LoginSignup
2
1

More than 1 year has passed since last update.

[API Gateway→ Lambda] Lambdaでクライアント情報を取得してみました

Posted at

場合によっては、Lambda Functionsでクライアント情報を取得する必要があります。
たとえば、クライアントのIPアドレスを確認します。

API Gateway(Lambda Proxy)→ Lambda Functions(Golang)を構築してみました。
Lambdaで、APIGatewayを呼び出したクライアントの情報を取得しました。

Golangのサンプルコード:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func handleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    strInfo1 := request.RequestContext.Identity.SourceIP
    strInfo2 := request.RequestContext.Identity.UserAgent
    strInfo3 := request.RequestContext.Identity.User
    strInfo4 := request.RequestContext.Identity.Caller
    
    result := fmt.Sprintf("IP: %s \nUserAgent: %s \nUser: %s \nCaller: %s\n", strInfo1, strInfo2, strInfo3, strInfo4)
    fmt.Sprintf("%s", result)
    return events.APIGatewayProxyResponse{Body: result, StatusCode: 200}, nil
}

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

結果は...
・ブラウザで
image.png
・CURLで

# curl -k https://ul7****d.execute-api.ap-northeast-1.amazonaws.com/prd
IP: 13.***.***.76
UserAgent: curl/7.79.1
User:
Caller: 

# curl ipconfig.io
13.***.***.76

PythonまたはNodeJSでIPを取得しようとしています。

参考ドキュメント:
[type APIGatewayRequestIdentity struct]
https://github.com/aws/aws-lambda-go/blob/bc1ec47cb1670c0d5eaca47c10d89789d8507c3d/events/apigw.go#L134

[Building Lambda functions with Go]
https://docs.aws.amazon.com/lambda/latest/dg/lambda-golang.html

[Using AWS Lambda with Amazon API Gateway]
https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html

2
1
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
2
1