Getting Started with DynamoDB in Go (Part 1 — Creating a Table)
In order to help you discover how you can use Go with DynamoDB I’m rewriting the Node.js tutorial for Go.
The first prerequisite is downloading and running DynamoDB locally in your computer as explained by Amazon AWS. It’s great that Amazon AWS gives you the chance to run DynamoDB in your local machine so you can learn how to use it for free.
I’ve started my DynamoDB using the following java command. DynamoDB will use port 8000 by default but you can use a different port if you want.
java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb
Initializing DynamoDB Local with the following configuration:
If you’re starting with Go please review the How to Write Code article about where you should store your source code. In this post I’m creating my main.go file inside my $GOPATH/src/github.com/doncicuto/dynamodb_tutorial path.
Also if it’s the first time you use DynamoDB you may start reading the following AWS article about the core components of DynamoDB.
Step 1. Create a Table
Once we have our DynamoDB instance working locally you can copy and paste the following program into the main.go. The code has the following flow:
- An Amazon configuration struct is created assigning the local endpoint which points to the default port 8000. Region is required but not used in this local example so you can use any of the available regions, for example us-west-2.
- A new Amazon AWS session is created.
- We create a connection to DynamoDB service using the session we’ve just created.
- Then we create the DynamoDB table definition where two attributes are used for describing a movie: a year and a title. Year will be our partition key and title will be our sort key. We also specify our initial read and write throughput settings. Please read the following Amazon AWS article for more information about DynamoDB Tables management.
- Finally we create the table using our table definition.
And finally go run your main.go
go run main.go
If the operation was successful you’ll see the result of creating the table in your local DynamoDB server.
CreationDateTime: 2018–01–22 07:21:17 +0000 UTC,
LastDecreaseDateTime: 1970–01–01 00:00:00 +0000 UTC,
LastIncreaseDateTime: 1970–01–01 00:00:00 +0000 UTC,
In the next part of the tutorial we’ll populate the Movies table.