我试图在Lambda中创建一个身份验证中间件,它基本上在ctx结构中注入一个属性ctx,并调用处理程序函数。我做得如何:
中间人/鉴定者:
package middlewares
import (
"context"
"github.com/aws/aws-lambda-go/events"
"github.com/passus/api/models"
)
func Authentication(next MiddlewareSignature) MiddlewareSignature {
user := models.User{}
return func(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
claims := request.RequestContext.Authorizer["claims"]
// Find user by claims properties.
if err := user.Current(claims); err != nil {
return events.APIGatewayProxyResponse{}, err
}
// Augment ctx with user property.
ctx = context.WithValue(ctx, "user", user)
return next(ctx, request)
}
}我的-兰博达。去吧:
package main
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/passus/api/middlewares"
)
func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
fmt.Println(ctx.user)
return events.APIGatewayProxyResponse{}, nil
}
func main() {
lambda.Start(
middlewares.Authentication(Handler),
)
}这种方法的问题在于:它不起作用。当我试图构建它时,我看到了以下错误:create/main.go:13:17: ctx.user undefined (type context.Context has no field or method user)
提前谢谢你。
发布于 2018-10-31 06:23:34
您不能直接访问添加到上下文中的值--您需要使用Value(key interface{}) interface{} API。
这是因为任何添加到Context的值都必须是不可变的,这样才能确保线程安全。对Context上现有值的任何更改都是通过创建一个新的Context来完成的。
这是更新的my-lambda.go
func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
fmt.Println(ctx.value("user").(models.User))
return events.APIGatewayProxyResponse{}, nil
}值返回一个接口,因此您需要使用类型断言。
注意:不建议在上下文中使用普通字符串作为键,因为这可能导致键冲突。
https://stackoverflow.com/questions/53074659
复制相似问题