After creating a Go project and initializing the module name, you can begin to import the necessary packages required for connecting to DynamoDb.
go get github.com/aws/aws-sdk-go/aws
go get github.com/aws/aws-sdk-go/aws/credentials
go get github.com/aws/aws-sdk-go/aws/session
go get github.com/aws/aws-sdk-go/service/dynamodb
The next step after getting the required dependencies is to create the method that can connect to DynamoDb.
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String("us-east-1"),
Credentials: credentials.NewStaticCredentials(
accessKey,
secretKey,
""),
}))
svc := dynamodb.New(sess)
return *svc
This creates a connection to DynamoDb using https. This session is created and can be used to read and write to your database.
Now we are going to try writing to our data.
func Write(data SomeDataStruct) {
input := &dynamodb.PutItemInput{
TableName: aws.String("TableName"),
Item: map[string]*dynamodb.AttributeValue{
"Property/Column": {
S: aws.String(data.Property),
},
"DifferentProperty": {
S: aws.String(data.DifferentProperty),
},
},
}
_, err := svc.PutItem(input)
if err != nil {
return
}
}
The code above will accept some data of type struct, for example, and map that data to properties in our database.
The &dynamodb.PutItemInput pointer allows us to define a variable named input of the PutItemInput struct type, and allows us to set the Item field on that struct to our actual data that we need to save.
Item field would be an example of our data structure in DynamoDb.
Next, we may want to read the data that we have written to our database. The function below allows us to do that.
func Read(limit int64) ([]map[string]*dynamodb.AttributeValue, error) {
input := &dynamodb.ScanInput{
TableName: aws.String("TableName"),
Limit: aws.Int64(limit),
}
result, err := svc.Scan(input)
if err != nil {
return nil, err
}
items := result.Items
return items, nil
}
Finally, we may just want to query a single item. To do that, all we have to do is create a pointer to a QueryInput struct, and define the attribute that we want to query on.
func ReadByAttribute(attrVal string) ([]map[string]*dynamodb.AttributeValue, error) {
input := &dynamodb.QueryInput{
TableName: aws.String("TableName"),
KeyConditionExpression: aws.String("AttributeVal = :attrVal"),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":attrVal": {
S: aws.String(attrVal),
},
},
}
result, err := svc.Query(input)
if err != nil {
return nil, err
}
return result.Items, nil
}
Our code accepts a parameter called attrVal, and queries our database based on a field named AttributeVal.
It will run a query that searches for the key AttributeVal, where the value of that key is equal to the value of attrVal that we passed in. It then returns every instance of that data.