我正在尝试使用 Golang 从 Lambda 将数据加载到 DynamoDB,但是编码方法只是生成空项。我有一个定义如下的类型结构......
type Flight struct {
id string
destination string
airline string
time string
latest string
}
然后我将填充一个 slice ,如下所示......
func PutToDynamo(Flights []Flight, kind string) {
Flights := []Flight{}
for _, row := range rows {
columns := row.FindAll("td")
f := columns[0].Text() //all these are strings
a := columns[1].Text()
i := columns[2].Text()
t := columns[4].Text()
l := columns[5].Text()
flight := Flight{
id: i,
destination: f,
airline: a,
time: t,
latest: l,
}
Flights = append(Flights, flight)
然后我尝试将其加载到 DynamoDB 中。
func PutToDynamo(flights []Flight, kind string) {
for _, flight := range flights {
av, err := dynamodbattribute.MarshalMap(flight)
input := &dynamodb.PutItemInput{
Item: av,
TableName: aws.String("flights"),
}
_, err = svc.PutItem(input)
fmt.Println("FLIGHT: ", input.GoString())
如果我打印航类,我可以看到我期望的所有信息。但是,input.GoString() 只是返回以下...
{
Item: {
},
TableName: "flights"
}
我在 lambda 中收到 DynamoDB 抛出的错误。
ValidationException: One or more parameter values were invalid: Missing the key id in the item
有什么想法吗?我尝试将 json:"id" 等放入结构中,但没有区别。
谢谢!
最佳答案
结构中的字段未导出,这可能是 dynamo marshal 未对其进行编码的原因(快速查看源代码表明 dynamo 和 json marshal 方法有点相似)。根据正则,golang json Marshal,来自documentation :
The json package only accesses the exported fields of struct types (those that begin with an uppercase letter). Therefore only the the exported fields of a struct will be present in the JSON output.
有两种方法可以解决这个问题:
a) 更改您的结构以导出字段。
type Flight struct {
Id string
Destination string
Airline string
Time string
Latest string
}
b) 如果您不想更改您的结构(例如,如果它在您的代码中引用了很多并且重构会很麻烦),您可以添加自定义 Marshal 和 Unmarhsal 函数并将您的结构隐藏在定制的导出结构之间(下面的代码未经测试 - 只是为了给出一个简短的想法):
type Flight struct {
id string
destination string
airline string
time string
latest string
}
type FlightExport struct {
Id string
Destination string
Airline string
Time string
Latest string
}
func(f *Flight) MarshalJSON()([] byte, error) {
fe: = &FlightExport {
ID: f.id,
Destination: f.destination,
Airline: f.airline,
Time: f.time,
Latest: f.latest
}
return json.Marshal(fe)
}
func(f *Flight) UnmarshalJSON(data[] byte) error {
var fe FlightExport
err: = json.Unmarshal(data, &fe)
if err != nil {
return err
}
f.id = fe.ID
f.destination = fe.Destination
f.airline = fe.Airline
f.time = fe.Time
f.latest = fe.Latest
return nil
}
关于amazon-web-services - Lambda Golang PutItem 和 MarshalMap 到 DynamoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51217707/