Reputation: 334
This might sound odd but I am developing an endpoint(REST) that allows users to download the file(may be a zip). So I am hitting an 3rd party API to get the file and then I have to pass that to end users.
I can't expose 3rd party APIs. I am quite new to Golang and REST APIs as well. I can explore the concept but anyone has any idea, what is the best way to allow download of file from your REST endpoint which is actually coming from 3rd party.
I know this is very bad way to ask question but I have no idea what should I explore or read any blog which gives me this idea.
I am not looking for code, but more of an idea.
Upvotes: 1
Views: 7438
Reputation: 444
you can do it simply with help of gin.Context.FileAttachment(path,filename)
Upvotes: 0
Reputation: 4189
Adding code snippet to what @Seaskyways has explained above.
return middleware.ResponderFunc(func(w http.ResponseWriter, r runtime.Producer) {
fn := filepath.Base(filePath)
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", fn))
io.Copy(w, file)
defer os.Remove(filePath)
file.Close()
})
May this help you.
Upvotes: 2
Reputation: 3795
Golang has the abstraction of io.Reader
which encapsulates almost anything that can be read in binary format.
Usually if you have a file coming from a 3rd party API, you would have at least one way to build an io.Reader
from that file, whether it's an HTTP request, gRPC, or local file.
If you have your io.Reader
, then definitely the requesting party would provide an io.Writer
to allow you to write the response they are requesting. After this point all you have to do is bridge the io.Reader
and io.Writer
to copy on the fly the file from the 3rd party API to the requesting party using io.Copy
or io.CopyN
for example.
Upvotes: 1