2

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?

delete
  • 18,144
  • 15
  • 48
  • 79
  • 3
    `body, err := ioutil.ReadAll(response.Body)` avoid this pattern. The answer below will stream the data from s3 to the web client without having to hold entire content in memory, so it will have significantly lower memory consumption on larger objects – erik258 Apr 02 '22 at 16:17

1 Answers1

3

You're almost done:

Instead of ctx.Write use this one:

ctx.DataFromReader(200, response.ContentLength, *response.ContentType, response.Body, nil)
itinance
  • 11,711
  • 7
  • 58
  • 98