DEV Community

Abhishek Gupta for AWS

Posted on • Originally published at community.aws

[20 Days of DynamoDB] Day 20 - Converting between Go and DynamoDB types

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:

  • MarshalMap converts Customer struct into a map[string]types.AttributeValue that's required by PutItem
  • UnmarshalMap converts the map[string]types.AttributeValue returned by GetItem into a Customer struct
    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)
Enter fullscreen mode Exit fullscreen mode

Recommended reading:

Top comments (0)