-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathclient.go
96 lines (78 loc) · 1.97 KB
/
client.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
89
90
91
92
93
94
95
96
// +build codegen
package aws
import (
"bytes"
"path/filepath"
"strings"
"text/template"
"github.com/jckuester/awsls/gen/util"
)
// GenerateClient returns Go code that initializes all AWS API clients.
func GenerateClient(outputPath string, services []string) {
err := util.WriteGoFile(
filepath.Join(outputPath, "client.go"),
util.CodeLayout,
"",
"aws",
clientGoCode(services),
)
if err != nil {
panic(err)
}
}
func clientGoCode(services []string) string {
var buf bytes.Buffer
err := clientTmpl.Execute(&buf, services)
if err != nil {
panic(err)
}
return strings.TrimSpace(buf.String())
}
var clientTmpl = template.Must(template.New("client").Funcs(
template.FuncMap{
"Title": strings.Title,
}).Parse(`import (
"context"
"fmt"
"github.com/apex/log"
"github.com/aws/aws-sdk-go-v2/aws/external"
"github.com/aws/aws-sdk-go-v2/service/sts"
{{range .}}"github.com/aws/aws-sdk-go-v2/service/{{.}}"
{{end}})
type Client struct {
AccountID string
Region string
Profile string
{{ range . }}{{ . | Title }}conn *{{.}}.Client
{{end}}}
func NewClient(configs ...external.Config) (*Client, error) {
cfg, err := external.LoadDefaultAWSConfig(configs...)
if err != nil {
return nil, fmt.Errorf("failed to load config: %s", err)
}
client := &Client{
{{ range . }}{{ . | Title }}conn: {{.}}.New(cfg),
{{end}}}
profile, _, err := external.GetSharedConfigProfile(configs)
if err != nil {
return nil, err
}
client.Profile = profile
client.Region = cfg.Region
log.WithFields(log.Fields{
"profile": profile,
"region": cfg.Region,
}).Debugf("created new instance of AWS client")
return client, nil
}
// SetAccountID populates the AccountID field of the client.
func (client *Client) SetAccountID() error {
req := client.Stsconn.GetCallerIdentityRequest(&sts.GetCallerIdentityInput{})
resp, err := req.Send(context.Background())
if err != nil {
return fmt.Errorf("failed to get caller identity: %s", err)
}
client.AccountID = *resp.Account
return nil
}
`))