给定以下用 Go 编写的简单 lambda,它只返回一个表描述...
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"go.uber.org/zap"
)
var (
dynamoDBTableName = aws.String(os.Getenv(EnvDynamoDBTableName))
logger = func() *zap.Logger {
l, err := zap.NewProduction()
if err != nil {
log.Printf("failed to create zap logger: %v", err)
}
return l
}()
)
func handler(ctx context.Context, req events.APIGatewayProxyRequest)
(events.APIGatewayProxyResponse, error) {
defer logger.Sync()
resp := events.APIGatewayProxyResponse{}
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
logger.Error("failed to load AWS config", zap.Error(err))
return resp, fmt.Errorf("failed to load AWS config: %w", err)
}
svc := dynamodb.NewFromConfig(cfg)
// fake logic
t, err := svc.DescribeTable(ctx, &dynamodb.DescribeTableInput{TableName: dynamoDBTableName})
if err != nil {
logger.Error("failed to describe table", zap.String("table-name", *dynamoDBTableName), zap.Error(err))
}
var sb strings.Builder
enc := json.NewEncoder(&sb)
err = enc.Encode(t.Table)
if err != nil {
logger.Error("failed to JSON encode response", zap.Error(err))
}
resp.Body = sb.String()
resp.StatusCode = http.StatusOK
return resp, nil
}
func main() {
lambda.Start(handler)
}
...如何在本地对其进行单元测试?使用旧的SDK,可以使用如下依赖注入:
type deps struct
svc dynamodbiface.DynamoDBAPI
table string
}
func (d *deps) handler(ctx context.Context, req events.APIGatewayProxyRequest)
(events.APIGatewayProxyResponse, error) {
...
}
如何测试使用新的适用于 Go V2 的 AWS 开发工具包编写的 lambda,因为我需要上下文来加载所需的配置?dynamodb.NewFromConfig
犯罪嫌疑人X
相关分类