Search code examples
amazon-web-servicesgoamazon-s3aws-sdk-go

How to get Amazon S3 file content after reading the object


I'm reading objects from Amazon S3 using the GetObject method from AWS SDK go v2

    input := &s3.GetObjectInput{
    Bucket: aws.String(w.Bucket),
    Key:    key,
}
object, _ := w.Client.GetObject(ctx, input)
return object

I have access to the object's content size, and to the file type, and there is a parameter

Object.Body

that should have the file content.. But I can't seem to find a way to access it.

the Body is of type io.ReadCloser


Solution

  • Add

    import "io/ioutil"
    

    Then

    bodyInBytes, err := ioutil.ReadAll(object.Body)
    

    If you are using go after 1.16 then io.ReadAll is preferred, import "io"

    You mention reading JSON in the comments. To read JSON, make a struct that matches the structure of your JSON document (use an online converter like https://mholt.github.io/json-to-go/ with a sample) then add import "encoding/json" and:

    data := mystruct{}
    err := json.Unmarshal(bodyInBytes, &data)