首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何恰当地增强上下文

如何恰当地增强上下文
EN

Stack Overflow用户
提问于 2018-10-31 00:28:42
回答 1查看 304关注 0票数 1

我试图在Lambda中创建一个身份验证中间件,它基本上在ctx结构中注入一个属性ctx,并调用处理程序函数。我做得如何:

中间人/鉴定者:

代码语言:javascript
复制
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)
    }
}

我的-兰博达。去吧:

代码语言:javascript
复制
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)

提前谢谢你。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-31 06:23:34

您不能直接访问添加到上下文中的值--您需要使用Value(key interface{}) interface{} API。

这是因为任何添加到Context的值都必须是不可变的,这样才能确保线程安全。对Context上现有值的任何更改都是通过创建一个新的Context来完成的。

这是更新的my-lambda.go

代码语言:javascript
复制
func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    fmt.Println(ctx.value("user").(models.User))

    return events.APIGatewayProxyResponse{}, nil
}

值返回一个接口,因此您需要使用类型断言。

注意:不建议在上下文中使用普通字符串作为键,因为这可能导致键冲突。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53074659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档