英文:
How to get Amazon S3 file content after reading the object
问题
我正在使用AWS SDK go v2的GetObject方法从Amazon S3中读取对象。
input := &s3.GetObjectInput{
Bucket: aws.String(w.Bucket),
Key: key,
}
object, _ := w.Client.GetObject(ctx, input)
return object
我可以访问对象的内容大小和文件类型,并且有一个参数
Object.Body
应该包含文件内容。但是我似乎找不到访问它的方法。
Body的类型是io.ReadCloser
。
英文:
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
答案1
得分: 1
添加
import "io/ioutil"
然后
bodyInBytes, err := ioutil.ReadAll(object.Body)
如果您使用的是1.16之后的版本,则首选io.ReadAll
,导入"io"
您在评论中提到了读取JSON。要读取JSON,请创建一个与JSON文档结构匹配的结构体(使用在线转换器,如https://mholt.github.io/json-to-go/,并提供一个示例),然后添加import "encoding/json"
和:
data := mystruct{}
err := json.Unmarshal(bodyInBytes, &data)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论