dounao1875 2019-09-15 09:12
浏览 44
已采纳

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

I want to test AWS Lambda in local environment using DynamoDB Local and SAM CLI. I create a simple user db table(id, name) and I'm trying to get the data.

I run "sam local start-api --env-vars test/env.json". When I access "http://localhost:3000/users/1", an error occured. Error message is below. I can't understand what this error message means. How do I fix this error?

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

This is my code.

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

  • 写回答

1条回答 默认 最新

  • doubu1970 2019-09-16 07:41
    关注

    That's been resolved.

    First Problem: can't read from the environment variable
    This was because the indent size deviation of template.yaml. Category "Events" and Category "Environment" had to be in line.

    Second Problem: error with "Function 'UserGetFunction' timed out after 5 seconds"
    This was because "localhost" expression. Rewriting "localhost" in env.json to "xxx.xxx.xxx.xxx" worked fine.("xxx.xxx.xxx.xxx" is ip address of your laptop)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件