For this example we create an EC2 client.
So the import becomes:
import (
"context"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/config"
)
Don’t forget the go get….
Main now has
package main
import (
"context"
"fmt"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/config"
)
var client *ec2.Client
func init(){
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
panic("configuration error, " + err.Error())
}
client = ec2.NewFromConfig(cfg)
}
func main() {
fmt.Println("vim-go")
}
1 package main
2
3 import (
4 "context"
5 "fmt"
6 "github.com/aws/aws-sdk-go-v2/service/ec2"
7 "github.com/aws/aws-sdk-go-v2/config"
8 )
9
10 var client *ec2.Client
11
12 func init(){
13 cfg, err := config.LoadDefaultConfig(context.TODO())
14 if err != nil {
15 panic("configuration error, " + err.Error())
16 }
17 client = ec2.NewFromConfig(cfg)
18
19 }
20
21 func main() {
22 fmt.Println("vim-go")
23 }
Because client is defined outside the functions, it is accessible from within the init function and the main function.
It is created as a pointer. Because the type is defined in the imported ec2 module, it is defined with:
10 var client *ec2.Client
This main program will compile and run, but do nothing useful at the moment. If you work with the vim editor, you get a default print in line 22.
See the full source on github.