使用go

时间:2018-02-28 19:10:38

标签: amazon-web-services go amazon-dynamodb

我正在使用以下代码在我的dynamodb表中创建一个项目:

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())
    }
}

但它正在返回错误:

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

我已经尝试在Record结构中声明Id,id和ID,但它不起作用。

陌生人是:我在官方文档中得到了这段代码(我正在更新以使用aws-sdk-go-v2)。

提前谢谢。

1 个答案:

答案 0 :(得分:0)

我不知道golang,但我在nodejs中遇到了类似的问题。

确保您在表格中添加的item包含“分区键”和sorting key,区分大小写。

编辑:

•这是一个golang问题,当DynamoDB列名称为小写时,item未正确构建。

•考虑重新定义Record结构(有关详细信息,请参阅this link):

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

其中idurl是DynamoDB表中的列名。