【问题标题】:How to properly augment context如何正确地增强上下文
【发布时间】:2019-04-04 02:32:49
【问题描述】:

我试图在我的 Lambda 中创建一个身份验证中间件,它基本上在 ctx 结构中注入一个属性 user,并调用处理函数。我最近怎么样:

middlewares/authentication.go:

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)
    }
}

my-lambda.go:

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)

提前谢谢你。

【问题讨论】:

  • 在宣布上下文包的博文中关注userIP example。将 userIP 替换为您的用户类型。

标签: go struct types


【解决方案1】:

您不能直接访问添加到上下文中的值 - 您需要使用 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
}

Value返回一个接口,所以需要使用类型断言。

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

【讨论】:

    猜你喜欢
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2014-06-20
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    相关资源
    最近更新 更多