Nic*_*ckS 4 go amazon-web-services amazon-dynamodb aws-lambda
我正在尝试使用 Golang 将数据从 Lambda 加载到 DynamoDB 中,但是编组方法只是生成空项目。我有一个类型结构定义如下...
type Flight struct {
id string
destination string
airline string
time string
latest string
}
Run Code Online (Sandbox Code Playgroud)
然后我填充一个切片如下.....
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)
Run Code Online (Sandbox Code Playgroud)
然后我尝试加载到 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())
Run Code Online (Sandbox Code Playgroud)
如果我打印航班,我可以看到我期望的所有信息。但是, input.GoString() 只是返回以下内容...
{
Item: {
},
TableName: "flights"
}
Run Code Online (Sandbox Code Playgroud)
我在 lambda 中收到了从 DynamoDB 抛出的错误。
ValidationException: One or more parameter values were invalid: Missing the key id in the item
Run Code Online (Sandbox Code Playgroud)
有任何想法吗??我试过将json:"id"etc 放入结构中,但没有区别。
谢谢!
结构中的字段未导出,这可能是 dynamo marshal 未对其进行封送处理的原因(快速查看源代码表明 dynamo 和 json marshal 方法有点相似)。根据常规,golang json Marshal,来自文档:
json 包仅访问结构类型的导出字段(以大写字母开头的字段)。因此,只有结构的导出字段才会出现在 JSON 输出中。
有两种方法可以解决这个问题:
a)将您的结构更改为具有导出的字段。
type Flight struct {
Id string
Destination string
Airline string
Time string
Latest string
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1586 次 |
| 最近记录: |