简体   繁体   中英

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

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?

You're almost done:

Instead of ctx.Write use this one:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM