DEV Community

Abhishek Gupta for AWS

Posted on • Originally published at community.aws

6 2

[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:

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay