读取对象后如何获取Amazon S3文件内容

huangapple go评论96阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2021年6月13日 05:30:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/67953156.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定