Skip to content

Instantly share code, notes, and snippets.

@Tamal
Created August 19, 2016 03:42
Show Gist options
  • Save Tamal/02776c3e2db7eec73c001225ff52e827 to your computer and use it in GitHub Desktop.
Save Tamal/02776c3e2db7eec73c001225ff52e827 to your computer and use it in GitHub Desktop.
Connect local dynamodb using Golang
package main
import (
"log"
"net/http"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
)
type appContext struct {
sess *session.Session
dbSvc *dynamodb.DynamoDB
}
func init() {
log.SetPrefix("appxxx => ")
log.SetFlags(log.Lmicroseconds | log.Lshortfile)
valid.SetFieldsRequiredByDefault(true)
}
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2"),
Endpoint: aws.String("http://localhost:8000")})
if err != nil {
log.Println(err)
return
}
dbSvc := dynamodb.New(sess)
result, err := dbSvc.ListTables(&dynamodb.ListTablesInput{})
if err != nil {
log.Println(err)
return
}
log.Println("Tables:")
for _, table := range result.TableNames {
log.Println(*table)
}
router := NewRouter(&appContext{sess: sess, dbSvc: dbSvc})
// Start web server
log.Println("Starting www...")
log.Fatal(http.ListenAndServe(":9001", router))
}
@philippgille
Copy link

Thanks @Tamal!

When the Docker container isn't running, the code blocks indefinitely at dbSvc.ListTables. As a Go beginner, I first had to figure out how to configure a timeout, because I couldn't find anything about timeout configuration in the SDK documentation. In case others are interested in the solution:

// ...
timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
result, err := dbSvc.ListTablesWithContext(timeoutCtx, &dynamodb.ListTablesInput{})
if err != nil {
	log.Println(err)
	return
}
// ...

@jarri-abidi
Copy link

Thanks @philippgille!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment