如何从Go Lambda中获取当前的Cognito用户

I'm having a hard time to get the current Cognito user attributes from within my lambda function, that is written in Go. I'm currently doing:

userAttributes = request.RequestContext.Authorizer["claims"]

And if I want to get the email:

userEmail = request.RequestContext.Authorizer["claims"].(map[string]interface{})["email"].(string)

I don't think this is a good way or even an acceptable way - it must have a better way to do it.

You can use 3rd party library to convert map[string]interface{} to a concrete type. Check the mitchellh/mapstructure library, it will help you to implement in a better way.

So, you could improve your code with this code :

import "github.com/mitchellh/mapstructure"

type Claims struct {
    Email string
    // other fields
    ID int
}

func claims(r request.Request) (Claims, error) {
    input := r.RequestContext.Authorizer["claims"]
    output := Claims{}
    err := mapstructure.Decode(input, &output)

    if err != nil {
        return nil, err
    }

    return output, nil
}

And somewhere in your handlers, you could get your claims by calling this method

func someWhere(){

    userClaims, err := claims(request)

    if err != nil {
        // handle
    }

    // you can now use : userClaims.Email, userClaims.ID
}

Don't forget to change func claims request parameter type according to yours (r parameter).