Skip to content

Instantly share code, notes, and snippets.

@girishramnani
Created September 28, 2019 08:01
Show Gist options
  • Save girishramnani/125f2433c3b71ce258f135913eba845c to your computer and use it in GitHub Desktop.
Save girishramnani/125f2433c3b71ce258f135913eba845c to your computer and use it in GitHub Desktop.
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"fmt"
)
type Item struct {
Year int
Title string
Plot string
Rating float64
}
func main() {
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
// Create DynamoDB client
svc := dynamodb.New(sess)
tableName := "Movies"
movieName := "The Big New Movie"
movieYear := "2015"
result, err := svc.GetItem(&dynamodb.GetItemInput{
TableName: aws.String(tableName),
Key: map[string]*dynamodb.AttributeValue{
"Year": {
N: aws.String(movieYear),
},
"Title": {
S: aws.String(movieName),
},
},
})
if err != nil {
fmt.Println(err.Error())
return
}
mydict := map[string]*dynamodb.AttributeValue{}
// @HERE you need to use the below struct to initialize the values that you care about.
// notice the "&", its used to get a pointer from an AttributeValue. My suggestion would be
// to explicitly set types where ever you can to reduce ambiguity
mydict["Year"] = &dynamodb.AttributeValue{
N: aws.String("2019"),
}
// snippet-end:[dynamodb.go.read_item.call]
// snippet-start:[dynamodb.go.read_item.unmarshall]
item := Item{}
err = dynamodbattribute.UnmarshalMap(result.Item, &item)
if err != nil {
panic(fmt.Sprintf("Failed to unmarshal Record, %v", err))
}
if item.Title == "" {
fmt.Println("Could not find '" + movieName + "' (" + movieYear + ")")
return
}
fmt.Println("Found item:")
fmt.Println("Year: ", item.Year)
fmt.Println("Title: ", item.Title)
fmt.Println("Plot: ", item.Plot)
fmt.Println("Rating:", item.Rating)
// snippet-end:[dynamodb.go.read_item.unmarshall]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment