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:

Billboard image

The fastest way to detect downtimes

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitoring.

Get started now

Top comments (0)

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay