Skip to content

Instantly share code, notes, and snippets.

@rhzs
Created July 22, 2023 11:53
Show Gist options
  • Save rhzs/e4c16525818cc6799609a47d2ef7a206 to your computer and use it in GitHub Desktop.
Save rhzs/e4c16525818cc6799609a47d2ef7a206 to your computer and use it in GitHub Desktop.
Golang S3 Download and Return as io.Reader
package aws
import (
"bytes"
"context"
"io"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
)
func Download(ctx context.Context, bucket string, item string, downloadPath string, environment string) (io.Reader, error) {
cfg := &aws.Config{}
cfg.WithCredentialsChainVerboseErrors(true)
// TODO: Replace with your region name
cfg.WithRegion(*aws.String("region-name"))
sess, err := session.NewSession(cfg)
if err != nil {
return nil, err
}
writeAtBuffer := &aws.WriteAtBuffer{}
_, err = s3manager.NewDownloader(sess).
Download(writeAtBuffer,
&s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(item),
})
if err != nil {
return nil, err
}
full := writeAtBuffer.Bytes()
return bytes.NewReader(full), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment