BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: DynamoDB Put Item

Go 1.23

Learn how to insert or replace items in an Amazon DynamoDB table using the AWS SDK for Go v2. This sample demonstrates how to marshal a Go struct into a DynamoDB item and execute the PutItem operation.

Code

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
    "github.com/aws/aws-sdk-go-v2/service/dynamodb"
)

// User defines the item structure
type User struct {
    ID    string `dynamodbav:"id"`
    Name  string `dynamodbav:"name"`
    Email string `dynamodbav:"email"`
    Age   int    `dynamodbav:"age"`
}

func main() {
    // Load AWS config
    cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion("us-east-1"))
    if err != nil {
        log.Fatalf("unable to load SDK config, %v", err)
    }

    // Create a DynamoDB client
    client := dynamodb.NewFromConfig(cfg)

    // Create a user item
    user := User{
        ID:    "123",
        Name:  "John Doe",
        Email: "[email protected]",
        Age:   30,
    }

    // Marshal the struct into a DynamoDB attribute map
    item, err := attributevalue.MarshalMap(user)
    if err != nil {
        log.Fatalf("failed to marshal item, %v", err)
    }

    // Put the item into the table
    _, err = client.PutItem(context.TODO(), &dynamodb.PutItemInput{
        TableName: aws.String("Users"),
        Item:      item,
    })
    if err != nil {
        log.Fatalf("failed to put item, %v", err)
    }

    fmt.Println("Successfully added item to table")
}

Explanation

Adding data to Amazon DynamoDB involves the PutItem operation, which creates a new item or replaces an existing one with the same primary key. The AWS SDK for Go v2 simplifies this process with the feature/dynamodb/attributevalue package, which allows you to easily convert standard Go structs into the format DynamoDB expects.

When defining your Go structs, you use struct tags (specifically dynamodbav) to map your struct fields to DynamoDB attributes. This is similar to how JSON tagging works in Go. The attributevalue.MarshalMap function then automatically traverses your struct and generates a map[string]types.AttributeValue, which is the required input format for the SDK's PutItem method.

It is best practice to initialize your DynamoDB client once and reuse it throughout your application to take advantage of connection pooling. Additionally, always handle errors gracefully, as operations can fail due to network issues, provisioned throughput limits, or conditional check failures if you are using condition expressions.

  • Struct Tags: Use dynamodbav tags to control how fields are named in the database.
  • Marshaling: Leverage attributevalue.MarshalMap to convert Go types to DynamoDB attributes automatically.
  • Client Reuse: Create the client once and pass it around to ensure efficient resource usage.

Code Breakdown

15
Defining the User struct with "dynamodbav" tags. These tags tell the SDK that the "ID" field should be stored as "id" in DynamoDB, "Name" as "name", and so on.
29
dynamodb.NewFromConfig(cfg) creates a new DynamoDB client. This client is thread-safe and should be reused across your application for better performance.
40
attributevalue.MarshalMap(user) converts the Go struct into a map[string]types.AttributeValue. This handles all the type conversions (e.g., int to Number, string to String) required by DynamoDB.
46
client.PutItem executes the operation. We pass the table name and the marshaled item map. If an item with the same primary key already exists, it will be completely replaced.