user8497169
user8497169

Reputation:

Create item in dynamodb using go

I'm using the follow code to create a item in my dynamodb table:

package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/aws/endpoints"
    "github.com/aws/aws-sdk-go-v2/aws/external"
    "github.com/aws/aws-sdk-go-v2/service/dynamodb"
    "github.com/aws/aws-sdk-go-v2/service/dynamodb/dynamodbattribute"
)

type Record struct {
    ID     string
    URLs   []string
}


// Using the SDK's default configuration, loading additional config
// and credentials values from the environment variables, shared
// credentials, and shared configuration files
var cfg, err = external.LoadDefaultAWSConfig()

func createNewExtraction() error {
    svc := dynamodb.New(cfg)

    r := Record{
        ID:   "ABC123",
        URLs: []string{
            "https://example.com/first/link",
            "https://example.com/second/url",
        },
    }
    item, err := dynamodbattribute.MarshalMap(r)
    if err != nil {
        panic(fmt.Sprintf("failed to DynamoDB marshal Record, %v", err))
    }

    req := svc.PutItemRequest(&dynamodb.PutItemInput{
        TableName: aws.String("test"), Item: item })

    _, err = req.Send(); if err != nil {
        return err
    }
    return nil
}

func main() {
    if len(cfg.Region) > 0 {
        // Set Region to us-east-1 as default.
        cfg.Region = endpoints.UsEast1RegionID
    }

    err = createNewExtraction(); if err != nil {
        panic(err.Error())
    }
}

But it's returning the error:

panic: ValidationException: One or more parameter values were invalid: Missing the key id in the item
    status code: 400, request id: F3VCQSGRIG5GM5PEJE7T5M4CEVVV4KQNSO5AEMVJF66Q9ASUAAJG

goroutine 1 [running]:
main.main()
    /Users/user/go/src/Test2/test.go:56 +0x102
exit status 2

I already tried to declare Id, id and ID in my Record struct, but it doesn't work.

The stranger is: I got this code in the official documentation (I'm updating to work with the aws-sdk-go-v2).

Thank you in advance.

Upvotes: 4

Views: 4818

Answers (1)

Costin
Costin

Reputation: 3029

I do not know golang, but I had similar problems in nodejs.

Make sure the item you put in the table contains the 'partition key' and the sorting key, case-sensitive.

EDIT:

• It is a golang issue, the item is not built properly when the DynamoDB column names are lowercase.

• Consider redefining the Record structure (see this link for details):

type Record struct{
    ID     string `json:"id"`
    URLs   []string `json:"url"`
}

where id and url are column names in DynamoDB table.

Upvotes: 7

Related Questions