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:

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay