github.com/aavshr/aws-sdk-go@v1.41.3/example/service/dynamodb/expression/scan.go (about) 1 //go:build example 2 // +build example 3 4 package main 5 6 import ( 7 "flag" 8 "fmt" 9 "os" 10 11 "github.com/aavshr/aws-sdk-go/aws" 12 "github.com/aavshr/aws-sdk-go/aws/session" 13 "github.com/aavshr/aws-sdk-go/service/dynamodb" 14 "github.com/aavshr/aws-sdk-go/service/dynamodb/expression" 15 ) 16 17 func exitWithError(err error) { 18 fmt.Fprintln(os.Stderr, err) 19 os.Exit(1) 20 } 21 22 func main() { 23 cfg := Config{} 24 if err := cfg.Load(); err != nil { 25 exitWithError(fmt.Errorf("failed to load config, %v", err)) 26 } 27 28 // Create the config specifying the Region for the DynamoDB table. 29 // If Config.Region is not set the region must come from the shared 30 // config or AWS_REGION environment variable. 31 awscfg := &aws.Config{} 32 if len(cfg.Region) > 0 { 33 awscfg.WithRegion(cfg.Region) 34 } 35 36 // Create the session that the DynamoDB service will use. 37 sess := session.Must(session.NewSession(awscfg)) 38 39 // Create the DynamoDB service client to make the query request with. 40 svc := dynamodb.New(sess) 41 42 // Create the Expression to fill the input struct with. 43 filt := expression.Name("Artist").Equal(expression.Value("No One You Know")) 44 proj := expression.NamesList(expression.Name("SongTitle"), expression.Name("AlbumTitle")) 45 expr, err := expression.NewBuilder().WithFilter(filt).WithProjection(proj).Build() 46 if err != nil { 47 exitWithError(fmt.Errorf("failed to create the Expression, %v", err)) 48 } 49 50 // Build the query input parameters 51 params := &dynamodb.ScanInput{ 52 ExpressionAttributeNames: expr.Names(), 53 ExpressionAttributeValues: expr.Values(), 54 FilterExpression: expr.Filter(), 55 ProjectionExpression: expr.Projection(), 56 TableName: aws.String(cfg.Table), 57 } 58 if cfg.Limit > 0 { 59 params.Limit = aws.Int64(cfg.Limit) 60 } 61 62 // Make the DynamoDB Query API call 63 result, err := svc.Scan(params) 64 if err != nil { 65 exitWithError(fmt.Errorf("failed to make Query API call, %v", err)) 66 } 67 68 fmt.Println(result) 69 } 70 71 type Config struct { 72 Table string // required 73 Region string // optional 74 Limit int64 // optional 75 } 76 77 func (c *Config) Load() error { 78 flag.Int64Var(&c.Limit, "limit", 0, "Limit is the max items to be returned, 0 is no limit") 79 flag.StringVar(&c.Table, "table", "", "Table to Query on") 80 flag.StringVar(&c.Region, "region", "", "AWS Region the table is in") 81 flag.Parse() 82 83 if len(c.Table) == 0 { 84 flag.PrintDefaults() 85 return fmt.Errorf("table name is required.") 86 } 87 88 return nil 89 }