英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论