|
| 1 | +package main |
| 2 | + |
| 3 | +// snippet-start:[dynamodb.go.read_item.imports] |
| 4 | +import ( |
| 5 | + "errors" |
| 6 | + |
| 7 | + "github.com/aws/aws-sdk-go/aws" |
| 8 | + "github.com/aws/aws-sdk-go/aws/session" |
| 9 | + "github.com/aws/aws-sdk-go/service/dynamodb" |
| 10 | + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" |
| 11 | + |
| 12 | + "fmt" |
| 13 | + "log" |
| 14 | +) |
| 15 | + |
| 16 | +// Create struct to hold info about new item |
| 17 | +type Item struct { |
| 18 | + Year int |
| 19 | + Title string |
| 20 | + Plot string |
| 21 | + Rating float64 |
| 22 | +} |
| 23 | + |
| 24 | +// snippet-end:[dynamodb.go.read_item.struct] |
| 25 | + |
| 26 | +func main() { |
| 27 | + |
| 28 | + // and region from the shared configuration file ~/.aws/config. |
| 29 | + sess := session.Must(session.NewSessionWithOptions(session.Options{ |
| 30 | + SharedConfigState: session.SharedConfigEnable, |
| 31 | + })) |
| 32 | + |
| 33 | + // Create DynamoDB client |
| 34 | + svc := dynamodb.New(sess) |
| 35 | + // snippet-end:[dynamodb.go.read_item.session] |
| 36 | + |
| 37 | + // snippet-start:[dynamodb.go.read_item.call] |
| 38 | + tableName := "Movies" |
| 39 | + movieName := "The Big New Movie" |
| 40 | + movieYear := "2015" |
| 41 | + |
| 42 | + result, err := svc.GetItem(&dynamodb.GetItemInput{ |
| 43 | + TableName: aws.String(tableName), |
| 44 | + Key: map[string]*dynamodb.AttributeValue{ |
| 45 | + "Year": { |
| 46 | + N: aws.String(movieYear), |
| 47 | + }, |
| 48 | + "Title": { |
| 49 | + S: aws.String(movieName), |
| 50 | + }, |
| 51 | + }, |
| 52 | + }) |
| 53 | + if err != nil { |
| 54 | + log.Fatalf("Got error calling GetItem: %s", err) |
| 55 | + } |
| 56 | + |
| 57 | + // snippet-start:[dynamodb.go.read_item.unmarshall] |
| 58 | + if result.Item == nil { |
| 59 | + msg := "Could not find '" + *title + "'" |
| 60 | + return nil, errors.New(msg) |
| 61 | + } |
| 62 | + |
| 63 | + item := Item{} |
| 64 | + |
| 65 | + err = dynamodbattribute.UnmarshalMap(result.Item, &item) |
| 66 | + if err != nil { |
| 67 | + panic(fmt.Sprintf("Failed to unmarshal Record, %v", err)) |
| 68 | + } |
| 69 | + |
| 70 | + fmt.Println("Found item:") |
| 71 | + fmt.Println("Year: ", item.Year) |
| 72 | + fmt.Println("Title: ", item.Title) |
| 73 | + fmt.Println("Plot: ", item.Plot) |
| 74 | + fmt.Println("Rating:", item.Rating) |
| 75 | + // snippet-end:[dynamodb.go.read_item.unmarshall] |
| 76 | +} |
| 77 | + |
| 78 | +// snippet-end:[dynamodb.go.read_item] |
0 commit comments