Skip to content

Instantly share code, notes, and snippets.

@niski84
Last active May 17, 2024 23:31
Show Gist options
  • Save niski84/894d94fa1bf1e84c70bcc534512be6a2 to your computer and use it in GitHub Desktop.
Save niski84/894d94fa1bf1e84c70bcc534512be6a2 to your computer and use it in GitHub Desktop.
read dynomodb record
package awsapi
import (
"fmt"
"log"
"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"
)
// QueryDynamoDB queries a DynamoDB table based on the provided key conditions and unmarshals the results into the provided output struct.
func QueryDynamoDB(region, tableName string, keyConditionExpression string, expressionAttributeValues map[string]*dynamodb.AttributeValue, output interface{}) error {
sess, err := session.NewSession(&aws.Config{
Region: aws.String(region),
})
if err != nil {
return fmt.Errorf("QueryDynamoDB: failed to create session: %w", err)
}
svc := dynamodb.New(sess)
input := &dynamodb.QueryInput{
TableName: aws.String(tableName),
KeyConditionExpression: aws.String(keyConditionExpression),
ExpressionAttributeValues: expressionAttributeValues,
}
result, err := svc.Query(input)
if err != nil {
return fmt.Errorf("QueryDynamoDB: failed to query table %s: %w", tableName, err)
}
err = dynamodbattribute.UnmarshalListOfMaps(result.Items, output)
if err != nil {
return fmt.Errorf("QueryDynamoDB: failed to unmarshal query result: %w", err)
}
return nil
}
type ConfigItem struct {
SiteType string `json:"SiteType"`
DomainPrefix string `json:"DomainPrefix"`
SiteName string `json:"SiteName"`
ModuleBaseURL string `json:"ModuleBaseURL"`
ModuleServicesEnabled bool `json:"ModuleServicesEnabled"`
ModuleServicesRemoteBucket string `json:"ModuleServicesRemoteBucketName"`
ModuleServicesComponentList []string `json:"ModuleServicesComponentList"`
ModuleServicesOtherSetting string `json:"ModuleServicesOtherSetting"`
}
func main() {
region := "us-west-2" // Replace with your AWS region
tableName := "EnvironmentConfig"
keyConditionExpression := "SiteType = :siteType AND DomainPrefix = :domainPrefix AND SiteName = :siteName"
expressionAttributeValues := map[string]*dynamodb.AttributeValue{
":siteType": {
S: aws.String("cfg"), // Replace with your SiteType value
},
":domainPrefix": {
S: aws.String("GOG"), // Replace with your DomainPrefix value
},
":siteName": {
S: aws.String("BankOne"), // Replace with your SiteName value
},
}
var items []ConfigItem
err := awsapi.QueryDynamoDB(region, tableName, keyConditionExpression, expressionAttributeValues, &items)
if err != nil {
log.Fatalf("Failed to query DynamoDB: %v", err)
}
for _, item := range items {
fmt.Printf("Retrieved item: %+v\n", item)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment