I've been looking for an excuse to use DynamoDB for awhile and I finally got a chance to this week. Previously I'd played around with it using IRB and the AWS Ruby SDK, but for my current project I'm integrating it into a Go application.
Unfortunately it didn't take long for me to realise that there isn't a mature package. I was able to find two, goamz and go-aws-sdk (created by the Stripe team which was recently adopted by Amazon as the basis for the official SDK)
Initially I thought I'd go with the (now) official SDK but after looking at the code I decided against it (didn't want to get involved with all the crazy Input/Output struct shenanigans), so I went with go-amz...which has almost no documentation for DynamoDB use either.
So I thought I'd share some notes on what I did and how I did it.
Setup the DynamoDB Connection
package main
import (
"github.com/goamz/goamz/aws"
"github.com/goamz/goamz/dynamodb"
"log"
)
func main() {
// This assumes you have ENV vars: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
auth, err := aws.EnvAuth()
if err != nil {
log.Panic(err)
}
ddbs := dynamodb.Server{auth, aws.USEast} // Initialize DynamoDB Server
userTableDesc, _ := ddbs.DescribeTable("users") // Create Table Description
userPK, _ := userTableDesc.BuildPrimaryKey() // Build the Primary Key
udb := ddbs.NewTable("dev-email", edbPK) // Get the handle for the Table
...
}
So now that we've got a handle for the Table, we can actually Get and Put data.
Put some data
type User struct {
Name string
Age int
}
func main () {
...
// Create user
u := &User{
Name: "Ali Hamidi",
Age: 31,
}
// Convert User Object to DynamoDB Attributes
ats, err := dynamodb.MarshalAttributes(u)
if err != nil {
log.Panic(err)
}
// Put Item
_, err = edb.PutItem("1", "1", ats)
if err != nil {
log.Panic(err)
}
}
Here we're marshalling a user object into a DynamoDB Attributes object and then calling PutItem
.