[英]Instantiating struct using constructor of embedded struct
I'm a Go newbie trying to override some methods in the AWS Go SDK for DynamoDB.我是 Go 新手,试图覆盖 DynamoDB 的 AWS Go SDK 中的一些方法。 Basically, I would like to add some logging to certain methods in the DynamoDB client.
基本上,我想在 DynamoDB 客户端的某些方法中添加一些日志记录。 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
?现在的问题是如何创建
dynamoDBLogger
? The only way to instantiate a DynamoDB
is by using a method:实例化
DynamoDB
的唯一方法是使用以下方法:
func New(...) *dynamodb.DynamoDB
in the dynamodb
package.在
dynamodb
package 中。 Can I somehow use that to build an instance of a dynamoDBLogger
?我可以以某种方式使用它来构建
dynamoDBLogger
的实例吗? Not sure if it'll work, but I would like for the *dynamoDbLogger
type to be usable as a *dynamodb.DynamoDB
.不确定它是否会起作用,但我希望
*dynamoDbLogger
类型可用作*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
}
ie the type system doesn't allow substituting a *dynamodb.DynamoDB
with a *dynamoDBLogger
.即类型系统不允许将
*dynamodb.DynamoDB
替换为*dynamoDBLogger
。 I'm wondering if Go's type system allows what I'm trying to accomplish, since dynamodb.DynamoDB
is not an interface?我想知道 Go 的类型系统是否允许我想要完成的工作,因为
dynamodb.DynamoDB
不是接口?
It is better to use dynamo db interface.最好使用 dynamo db 接口。 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/完整示例在: https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/dynamodbiface/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.