amazon-web-services - 我无法读取环境变量(Go 中的 aws-lambda)

标签 amazon-web-services go aws-lambda aws-api-gateway dynamo-local

我想使用 DynamoDB Local 和 SAM CLI 在本地环境中测试 AWS Lambda。 我创建了一个简单的用户数据库表(id,名称),我正在尝试获取数据。

我运行“sam local start-api --env-vars test/env.json”。当我访问“http://localhost:3000/users/1”时,发生错误。错误信息如下。我无法理解此错误消息的含义。如何修复此错误?

{
  "errorMessage": "InvalidParameter: 1 validation error(s) found.\n- minimum field size of 3, GetItemInput.TableName.\n",
  "errorType": "ErrInvalidParams"
}

这是我的代码。

func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Environment variables
    endpoint := os.Getenv("DYNAMODB_ENDPOINT")
    tableName := os.Getenv("DYNAMODB_TABLE_NAME")

    // Request
    id, _ := request.PathParameters["id"]

    // DynamoDB
    sess := session.Must(session.NewSession())
    config := aws.NewConfig().WithRegion("ap-northeast-1")
    if len(endpoint) > 0 {
        config = config.WithEndpoint(endpoint)
    }

    db := dynamodb.New(sess, config)
    response, err := db.GetItem(&dynamodb.GetItemInput{
        TableName: aws.String(tableName),
        Key: map[string]*dynamodb.AttributeValue{
            "Id": {
                N: aws.String(string(id)),
            },
        },
        AttributesToGet: []*string{
            aws.String("Id"),
            aws.String("Name"),
        },
        ConsistentRead:         aws.Bool(true),
        ReturnConsumedCapacity: aws.String("NONE"),
    })
    if err != nil {
        return events.APIGatewayProxyResponse{}, err
    }

    user := User{}
    err = dynamodbattribute.Unmarshal(&dynamodb.AttributeValue{M: response.Item}, &user)
    if err != nil {
        return events.APIGatewayProxyResponse{}, err
    }

    // Json
    bytes, err := json.Marshal(user)
    if err != nil {
        return events.APIGatewayProxyResponse{}, err
    }

    return events.APIGatewayProxyResponse{
        Body:       string(bytes),
        StatusCode: 200,
    }, nil
}

error message

最佳答案

已经解决了。

第一个问题:无法读取环境变量
这是因为 template.yaml 的缩进尺寸偏差。类别“事件”和类别“环境”必须对齐。

第二个问题:“函数‘UserGetFunction’在 5 秒后超时”错误
这是因为“localhost”的表达。将 env.json 中的“localhost”重写为“xxx.xxx.xxx.xxx”工作正常。(“xxx.xxx.xxx.xxx”是您笔记本电脑的 ip 地址)

关于amazon-web-services - 我无法读取环境变量(Go 中的 aws-lambda),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57942700/

相关文章:

amazon-web-services - 设置 Lambda 以在没有 IAM 策略的情况下创建 AWS CloudFormation

amazon-web-services - 如何在多个Lambda函数之间共享代码?

node.js - 出现错误 : Stream yields empty buffer when resizing images from S3 with local node service

amazon-web-services - "No basic auth credentials"在 EC2 实例上使用 IAM 角色

javascript - Uncaught Error : Script error for "aws-sdk"

go - 未找到类型 InteractionCallback,atom 正在删除导入语句

github - 如何使用带有默认消息的集线器发送拉取请求(无需打开文本编辑器)?

amazon-web-services - 描述在 Fargate/Lambda 中执行 DataSync 任务时出现 ENI 错误

amazon-web-services - 如何解锁 VPC 中 Redshift 集群上的 Kinesis Firehose CIDR/IP?

go - 如何从 yaml 解码嵌入式结构