如何适当地增加上下文

时间:2018-10-31 00:28:42

标签: go struct types

我正在尝试在Lambda中创建身份验证中间件,该中间件基本上是在<h3 class="outfitsbuttonsheadings"> <span class="outfitsbuttonsheadings">Autumn outfits</span> <br> <span class="date">23 September, 2018</span> </h3>结构中注入属性user,并调用处理程序函数。我的状况:

middlewares / authentication.go:

ctx

my-lambda.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)
    }
}

这种方法的问题是:它不起作用。尝试构建该错误时,我看到以下错误: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), ) }

谢谢。

1 个答案:

答案 0 :(得分:1)

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

这是因为添加到Context的任何值都必须是不可变的,以确保线程安全。通过创建新的ContextContext上的现有值进行任何更改。

这是更新的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
}

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

注意:不建议将纯字符串用作Context上的键,因为这可能会导致键冲突。