我正在尝试编写一个非常简单的 Go 函数来将条目插入到 DynamoDB 表中。

我正在遵循 AWS 文档站点上提供的教程,但由于某种原因,函数 dynamodbattribute.MarshalMap 返回了一个空映射。

代码编译并运行,但在尝试插入记录时中断,因为它在映射中找不到所需的键。一个小的 println Action 显示映射是空的,即使它的创建结构不是。

任何帮助表示赞赏!

package main

import (
    "context"
    "fmt"

    "github.com/aws/aws-sdk-go/aws"

    "github.com/aws/aws-lambda-go/lambda"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)

// Item Struct for Fruit Item
type Item struct {
    fruitID   int
    fruitName string
}

/*HandleRequest handles the lambda request.*/
func HandleRequest(ctx context.Context) (string, error) {
    // Initialize a session that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials
    // and region from the shared configuration file ~/.aws/config.
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    // Create DynamoDB client
    svc := dynamodb.New(sess)

    item := Item{
        fruitID:   2,
        fruitName: "Orange",
    }

    fmt.Println(item)

    av, err := dynamodbattribute.MarshalMap(item)
    if err != nil {
        fmt.Println("Got error marshalling new fruit item: ")
        fmt.Println(err.Error())
        return "", err
    }

    fmt.Println("av: ", av)
    fmt.Println("ln: ", len(av))
    fmt.Println("KEY VALUE PAIRS::")
    for key, value := range av {
        fmt.Println("Key:", key, "Value:", value)
    }

    tableName := "fruits"

    input := &dynamodb.PutItemInput{
        Item:      av,
        TableName: aws.String(tableName),
    }

    _, err = svc.PutItem(input)
    if err != nil {
        fmt.Println("Got error inserting new fruit item: ")
        fmt.Println(err.Error())
        return "", err
    }

    return "SUCCESS!", nil
}

func main() {
    lambda.Start(HandleRequest)
}

Lambda 的日志输出
START RequestId: 82f120d9-6bba-40d9-9204-136d491dbb88 Version: $LATEST
{2 Orange}
av:  map[]
ln:  0
KEY VALUE PAIRS::
Got error inserting new fruit item:
ValidationException: One or more parameter values were invalid: Missing the key fruitId in the item
    status code: 400, request id: QUJG8R8EHPO65O1JFVI98PRQ1VVV4KQNSO5AEMVJF66Q9ASUAAJG
ValidationException: One or more parameter values were invalid: Missing the key fruitId in the item
    status code: 400, request id: QUJG8R8EHPO65O1JFVI98PRQ1VVV4KQNSO5AEMVJF66Q9ASUAAJG: requestError
null
END RequestId: 82f120d9-6bba-40d9-9204-136d491dbb88

最佳答案

struct 中以大写字母开头的字段只能导出,可以在此包之外使用。

你可以试试这个结构,看看它是否有效?

type Item struct {
    FruitID   int
    FruitName string
}

关于go - dynamodbattribute.MarshalMap 返回空 map ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59140779/

10-12 17:04