eof
eof

Reputation: 557

Instantiating struct using constructor of embedded struct

I'm a Go newbie trying to override some methods in the AWS Go SDK for DynamoDB. Basically, I would like to add some logging to certain methods in the DynamoDB client. The code that I have is:

type dynamoDBLogger struct {
  dynamodb.DynamoDB
}

func (d *dynamoDBLogger) DeleteItemWithContext(ctx context.Context, item *dynamodb.DeleteItemInput) (*dynamodb.DeleteItemOutput, error) {
    logger.Debug("Deleting from DynamoDB: %+v", *item)
    return d.DynamoDB.DeleteItemWithContext(ctx, item)
}

In other words, it just adds a logging statement before the actual call. This code compiles. The problem is now how can I create a dynamoDBLogger? The only way to instantiate a DynamoDB is by using a method:

func New(...) *dynamodb.DynamoDB

in the dynamodb package. Can I somehow use that to build an instance of a dynamoDBLogger? Not sure if it'll work, but I would like for the *dynamoDbLogger type to be usable as a *dynamodb.DynamoDB.

EDIT: I actually noticed that the following fails:

func GetDynamoClient(sess *session.Session) *dynamodb.DynamoDB {
    svc := dynamoDBLogger{}
    svc.DynamoDB = *dynamodb.New(sess)
    return &svc
}

i.e. the type system doesn't allow substituting a *dynamodb.DynamoDB with a *dynamoDBLogger. I'm wondering if Go's type system allows what I'm trying to accomplish, since dynamodb.DynamoDB is not an interface?

Upvotes: 1

Views: 272

Answers (1)

serge-v
serge-v

Reputation: 780

It is better to use dynamo db interface. It gives a possibility to create mocks for tests. Example:

package main

import (
    "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
)

type dynamoDBLogger struct {
    DynamoDBAPI
}

func NewDynamoDB() dynamodbiface.DynamoDBAPI {
    svc := &dynamoDBLogger{
        DynamoDBAPI: dynamodb.New(sess),
    }
    return &svc
}

// in tests

type mockDB struct {
    dynamodbiface.DynamoDBAPI
}

func NewMockDB() dynamodbiface.DynamoDBAPI {
}

In mock you need to implement the only methods that actually is used in the program.

Full example is on: https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/dynamodbiface/

Upvotes: 1

Related Questions