amazon-web-servicesgoaws-lambdaaws-api-gatewaydynamo-local

I can't read from the environment variable (aws-lambda in Go)


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.\n- minimum field size of 3, GetItemInput.TableName.\n",
  "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


Solution

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