Created
September 6, 2020 10:21
-
-
Save subzero112233/3b95553c33d0425b0a6e71a628c45e02 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"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" | |
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" | |
) | |
var ( | |
conf *Config | |
err error | |
) | |
type Config struct { | |
DynamoDB dynamodbiface.DynamoDBAPI | |
} | |
type Item struct { | |
PlayerName struct { | |
Value string | |
} | |
JerseyNumber struct { | |
Value string | |
} | |
} | |
func InitializeConfig() (*Config, error) { | |
sess, err := session.NewSession(&aws.Config{ | |
Region: aws.String("us-east-1")}, | |
) | |
if err != nil { | |
return &Config{}, fmt.Errorf("unable to create a session to aws with error: %v", err) | |
} | |
return &Config{ | |
DynamoDB: dynamodb.New(sess), | |
}, nil | |
} | |
func getItem(conf *Config, table string, item *Item) (map[string]string, error) { | |
var m map[string]string | |
result, err := conf.DynamoDB.GetItem(&dynamodb.GetItemInput{ | |
TableName: aws.String(table), | |
Key: map[string]*dynamodb.AttributeValue{ | |
"PlayerName": { | |
S: aws.String(item.PlayerName.Value), | |
}, | |
"JerseyNumber": { | |
N: aws.String(item.JerseyNumber.Value), | |
}, | |
}, | |
}) | |
if err != nil { | |
return m, fmt.Errorf("failed to get item from dynamodb: %s", err) | |
} | |
err = dynamodbattribute.UnmarshalMap(result.Item, &m) | |
if err != nil { | |
return m, fmt.Errorf("failed to marshal map of the item in table struct, error: %s", err) | |
} | |
return m, nil | |
} | |
func init() { | |
conf, err = InitializeConfig() | |
if err != nil { | |
panic(fmt.Sprintf("unable to initalize the configuration")) | |
} | |
} | |
func main() { | |
i := &Item{} | |
i.PlayerName.Value = "Manu Ginobili" | |
i.JerseyNumber.Value = "20" | |
item, err := getItem(conf, "SanAntonioSpurs", i) | |
if err != nil { | |
fmt.Printf("error while trying to retrieve item from dynamodb: %v", err) | |
} | |
fmt.Println(item) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment