Posted: 13/Feb/2024
The DynamoDB attributevalue in the AWS SDK for Go package can save you a lot of time, thanks to the Marshal and Unmarshal family of utility functions that can be used to convert between Go types (including structs) and AttributeValues.
Here is an example using a Go struct:
-
MarshalMapconverts Customerstructinto amap[string]types.AttributeValuethat's required byPutItem -
UnmarshalMapconverts themap[string]types.AttributeValuereturned byGetIteminto a Customerstruct
type Customer struct {
Email string `dynamodbav:"email"`
Age int `dynamodbav:"age,omitempty"`
City string `dynamodbav:"city"`
}
customer := Customer{Email: "abhirockzz@gmail.com", City: "New Delhi"}
item, _ := attributevalue.MarshalMap(customer)
client.PutItem(context.Background(), &dynamodb.PutItemInput{
TableName: aws.String(tableName),
Item: item,
})
resp, _ := client.GetItem(context.Background(), &dynamodb.GetItemInput{
TableName: aws.String(tableName),
Key: map[string]types.AttributeValue{"email": &types.AttributeValueMemberS{Value: "abhirockzz@gmail.com"}},
})
var cust Customer
attributevalue.UnmarshalMap(resp.Item, &cust)
log.Println("item info:", cust.Email, cust.City)
Recommended reading:
- MarshalMap API doc
- UnmarshalMap API doc
- AttributeValue API doc
Top comments (0)