在AWS Lambda函数中获取请求者的IP地址

huangapple go评论97阅读模式
英文:

Getting requester's IP address in AWS lambda function

问题

我理解了,根据这个问题的答案,我可以通过以下方式获取调用者的 IP 地址:

events['headers']['X-Forwarded-For']

对于 Go 语言,这个信息应该在接受 context.Context 参数的 lambda 函数的上下文中。然而,在文档中我没有看到任何关于请求头的提及。在 Go 的 lambda 函数中有没有获取相同信息的方法呢?

英文:

I understand, from the answer to this question, that I can get the IP address of the caller of a node.js lambda function by doing this:

events['headers']['X-Forwarded-For']

It seems like, for Go, this information should be inside the context.Context for lambda signatures that take it. However, looking at the documentation, I don't see any mention of request headers. Is there a way to get the same information in a Go lambda function?

答案1

得分: 0

在自己进行了一些研究后,我发现我需要将我的 Lambda 函数放在 API Gateway 实例后面,以获取我感兴趣的信息。在这样做之后,我可以像这样修改处理程序:

package main

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

func LambdaHandler(ctx context.Context, request events.APIGatewayV2HTTPRequest) (int, error) {

    // 一些代码

	addr := request.RequestContext.HTTP.SourceIP

    // 其他一些代码

    return 0, nil
}

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

通过这样做,API Gateway 将填充我所需的所有请求元数据,并将其传递给我的 Lambda 函数。请求正文现在包含在 request.Body 中,因此我可以使用 JSON 反序列化或其他编码方法提取该数据。

英文:

After doing some research on my own, I figured out that I needed to put my lambda function behind an API Gateway instance to get the information I was interested in. After doing that, I could modify the handler like this:

package main

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

func LambdaHandler(ctx context.Context, request events.APIGatewayV2HTTPRequest) (int, error) {

    // some code

	addr := request.RequestContext.HTTP.SourceIP

    // some other code

    return 0
}

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

By doing this, the API gateway will populate all the request metadata I need and pass that on to my lambda function. The request body is now contained in request.Body so I can extract that data using JSON deserialization or whatever other method my data is encoded as.

huangapple
  • 本文由 发表于 2023年1月31日 15:10:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75293713.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定