Created
September 9, 2025 11:41
-
-
Save 42LM/4077775629cda60d395feff7dc30d61d to your computer and use it in GitHub Desktop.
go dynamodb client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "context" | |
| "fmt" | |
| "os" | |
| "github.com/aws/aws-sdk-go-v2/aws" | |
| "github.com/aws/aws-sdk-go-v2/config" | |
| "github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue" | |
| "github.com/aws/aws-sdk-go-v2/service/dynamodb" | |
| "github.com/aws/aws-sdk-go-v2/service/dynamodb/types" | |
| ) | |
| type DynamoDBClient struct { | |
| client *dynamodb.Client | |
| } | |
| func New(endpointURL string) *DynamoDBClient { | |
| cfg, err := config.LoadDefaultConfig(context.Background()) | |
| if err != nil { | |
| panic(err) | |
| } | |
| dynamodbEndpointResolver := getEndpointResolver(endpointURL) | |
| // Using the Config value, create the DynamoDB client. | |
| client := dynamodb.NewFromConfig( | |
| cfg, | |
| dynamodb.WithEndpointResolver(dynamodbEndpointResolver), | |
| ) | |
| return &DynamoDBClient{client} | |
| } | |
| func main() { | |
| db := New(os.Getenv("DATABASE_AWS_DYNAMODB_ENDPOINT")) | |
| marshaledId, err := attributevalue.Marshal("0") | |
| if err != nil { | |
| panic(err) | |
| } | |
| resp, err := db.client.GetItem(context.Background(), &dynamodb.GetItemInput{ | |
| Key: map[string]types.AttributeValue{"id": marshaledId}, | |
| TableName: aws.String("test"), | |
| ConsistentRead: aws.Bool(true), | |
| }) | |
| // var notFound *types.ResourceNotFoundException | |
| // if !errors.As(err, ¬Found) { | |
| // panic(err) | |
| // } | |
| // for more information about struct tag `dynamodbav` check: | |
| // https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue#Marshal | |
| if resp != nil { | |
| data := struct { | |
| ID string `dynamodbav:"id"` | |
| Foo string `dynamodbav:"foo"` | |
| Peon string `dynamodbav:"peon"` | |
| }{} | |
| attributevalue.UnmarshalMap(resp.Item, &data) | |
| fmt.Println(data) | |
| } | |
| } | |
| // getEndpointResolver returns the default endpoint if endpoint is empty | |
| func getEndpointResolver(endpointURL string) dynamodb.EndpointResolver { | |
| if endpointURL != "" { | |
| return dynamodb.EndpointResolverFromURL(endpointURL) | |
| } | |
| return dynamodb.NewDefaultEndpointResolver() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment