1// +build example 2 3package main 4 5import ( 6 "flag" 7 "fmt" 8 "os" 9 10 "github.com/aws/aws-sdk-go/aws" 11 "github.com/aws/aws-sdk-go/aws/session" 12 "github.com/aws/aws-sdk-go/service/dynamodb" 13 "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" 14) 15 16func exitWithError(err error) { 17 fmt.Fprintln(os.Stderr, err) 18 os.Exit(1) 19} 20 21func main() { 22 cfg := Config{} 23 if err := cfg.Load(); err != nil { 24 exitWithError(fmt.Errorf("failed to load config, %v", err)) 25 } 26 27 // Create the config specifying the Region for the DynamoDB table. 28 // If Config.Region is not set the region must come from the shared 29 // config or AWS_REGION environment variable. 30 awscfg := &aws.Config{} 31 if len(cfg.Region) > 0 { 32 awscfg.WithRegion(cfg.Region) 33 } 34 35 // Create the session that the DynamoDB service will use. 36 sess := session.Must(session.NewSession(awscfg)) 37 38 // Create the DynamoDB service client to make the query request with. 39 svc := dynamodb.New(sess) 40 41 // Build the query input parameters 42 params := &dynamodb.ScanInput{ 43 TableName: aws.String(cfg.Table), 44 } 45 if cfg.Limit > 0 { 46 params.Limit = aws.Int64(cfg.Limit) 47 } 48 49 // Make the DynamoDB Query API call 50 result, err := svc.Scan(params) 51 if err != nil { 52 exitWithError(fmt.Errorf("failed to make Query API call, %v", err)) 53 } 54 55 items := []Item{} 56 57 // Unmarshal the Items field in the result value to the Item Go type. 58 err = dynamodbattribute.UnmarshalListOfMaps(result.Items, &items) 59 if err != nil { 60 exitWithError(fmt.Errorf("failed to unmarshal Query result items, %v", err)) 61 } 62 63 // Print out the items returned 64 for i, item := range items { 65 fmt.Printf("%d: Key: %d, Desc: %s\n", i, item.Key, item.Desc) 66 fmt.Printf("\tNum Data Values: %d\n", len(item.Data)) 67 for k, v := range item.Data { 68 fmt.Printf("\t- %q: %v\n", k, v) 69 } 70 } 71} 72 73type Item struct { 74 Key int 75 Desc string 76 Data map[string]interface{} 77} 78 79type Config struct { 80 Table string // required 81 Region string // optional 82 Limit int64 // optional 83 84} 85 86func (c *Config) Load() error { 87 flag.Int64Var(&c.Limit, "limit", 0, "Limit is the max items to be returned, 0 is no limit") 88 flag.StringVar(&c.Table, "table", "", "Table to Query on") 89 flag.StringVar(&c.Region, "region", "", "AWS Region the table is in") 90 flag.Parse() 91 92 if len(c.Table) == 0 { 93 flag.PrintDefaults() 94 return fmt.Errorf("table name is required.") 95 } 96 97 return nil 98} 99