linzhengen / tech-notes

My tech notes write in github issues🧲
1 stars 0 forks source link

[20210610] golang-aws-sdk-v2でlocalstackへ接続方法 #108

Open linzhengen opened 3 years ago

linzhengen commented 3 years ago

参考

https://www.linkedin.com/pulse/how-setup-golang-aws-sdk-v2-localstack-local-phuc-hai-huynh

func init() {
    awsRegion = os.Getenv("AWS_REGION")
    awsEndpoint = os.Getenv("AWS_ENDPOINT")
    bucketName = os.Getenv("S3_BUCKET")

    customResolver := aws.EndpointResolverFunc(func(service, region string) (aws.Endpoint, error) {
        if awsEndpoint != "" {
            return aws.Endpoint{
                PartitionID:   "aws",
                URL:           awsEndpoint,
                SigningRegion: awsRegion,
            }, nil
        }

        // returning EndpointNotFoundError will allow the service to fallback to it's default resolution
        return aws.Endpoint{}, &aws.EndpointNotFoundError{}
    })

    awsCfg, err := config.LoadDefaultConfig(context.TODO(),
        config.WithRegion(awsRegion),
        config.WithEndpointResolver(customResolver),
        // これれはないと `no EC2 IMDS role found`のエラーが発生、"key", "secret", "session"は任意の値でOK
        config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("key", "secret", "session")),
    )
    if err != nil {
        log.Fatalf("Cannot load the AWS configs: %s", err)
    }

    s3svc = s3.NewFromConfig(awsCfg, func(o *s3.Options) {
        o.UsePathStyle = true
    })
}