如何通过GIN-Router将AWS S3中的文件作为二进制流发送到浏览器?

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

Go: How to send a File from AWS S3 via GIN-Router as binary stream to the browser?

问题

你可以使用ctx.Data方法将文件作为二进制响应发送给Gin。以下是如何将从S3接收到的文件发送为二进制响应的示例代码:

response, err := i.s3Client.GetObject(context.TODO(), &s3.GetObjectInput{
	Bucket: aws.String("test"),
	Key:    aws.String(filename),
})

if err != nil {
	ctx.JSON(http.StatusBadRequest, err)
	return
}

defer response.Body.Close()

data, err := ioutil.ReadAll(response.Body)
if err != nil {
	ctx.JSON(http.StatusInternalServerError, err)
	return
}

ctx.Data(http.StatusOK, *response.ContentType, data)

这将使用ctx.Data方法将文件数据作为二进制响应发送给客户端。确保在处理完响应后关闭response.Body以释放资源。

英文:

How can I send a file, that I've got received from S3, to Gin as binary response?

Lets say, I have the following code to obtain an image from S3 bucket:

response, err := i.s3Client.GetObject(context.TODO(), &s3.GetObjectInput{
	Bucket: aws.String("test"),
	Key:    aws.String(filename),
})

How can I pipe this response into the response context of Gin-router?

I could do something like:

body, err := ioutil.ReadAll(response.Body)
if err != nil {
	ctx.JSON(http.StatusBadRequest, err)
	return
}

But how to tell gin to serve this as output? What comes in my mind but won't work is:

ctx.Header("Content-Type", *response.ContentType)
ctx.Header("Cache-control", "max-age="+strconv.Itoa(60*60*24*365))
ctx.Write(body)

Anything I can do here?

答案1

得分: 3

你快要完成了:

不要使用ctx.Write,而是使用以下代码:

ctx.DataFromReader(200, response.ContentLength, *response.ContentType, response.Body, nil)
英文:

You're almost done:

Instead of ctx.Write use this one:

ctx.DataFromReader(200, response.ContentLength, *response.ContentType, response.Body, nil)

huangapple
  • 本文由 发表于 2022年4月2日 23:40:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/71718946.html
匿名

发表评论

匿名网友

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

确定