-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamo_config.go
88 lines (74 loc) · 1.94 KB
/
dynamo_config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package ginboot
import (
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"golang.org/x/net/context"
)
type DynamoConfig struct {
Region string
AccessKeyID string
SecretAccessKey string
Endpoint string
Profile string
}
func NewDynamoConfig() *DynamoConfig {
return &DynamoConfig{
Region: "us-east-1",
Endpoint: "http://localhost:8000",
}
}
func (c *DynamoConfig) WithRegion(region string) *DynamoConfig {
c.Region = region
return c
}
func (c *DynamoConfig) WithCredentials(accessKeyID, secretAccessKey string) *DynamoConfig {
c.AccessKeyID = accessKeyID
c.SecretAccessKey = secretAccessKey
return c
}
func (c *DynamoConfig) WithEndpoint(endpoint string) *DynamoConfig {
c.Endpoint = endpoint
return c
}
func (c *DynamoConfig) WithProfile(profile string) *DynamoConfig {
c.Profile = profile
return c
}
func (c *DynamoConfig) Connect() (*dynamodb.Client, error) {
ctx := context.Background()
var cfg aws.Config
var err error
if c.Profile != "" {
cfg, err = config.LoadDefaultConfig(ctx,
config.WithRegion(c.Region),
config.WithSharedConfigProfile(c.Profile),
)
} else if c.AccessKeyID != "" && c.SecretAccessKey != "" {
cfg, err = config.LoadDefaultConfig(ctx,
config.WithRegion(c.Region),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
c.AccessKeyID,
c.SecretAccessKey,
"",
)),
)
} else {
cfg, err = config.LoadDefaultConfig(ctx, config.WithRegion(c.Region))
}
if err != nil {
return nil, fmt.Errorf("failed to load AWS config: %v", err)
}
options := &dynamodb.Options{
Credentials: cfg.Credentials,
Region: cfg.Region,
}
if c.Endpoint != "" {
options.EndpointResolver = dynamodb.EndpointResolverFromURL(c.Endpoint)
}
return dynamodb.NewFromConfig(cfg, func(o *dynamodb.Options) {
*o = *options
}), nil
}