Vinay
Vinay

Reputation: 334

Allow to download file from my REST endpoint in Golang using 3rd party API

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

Answers (3)

Aman Agarwal
Aman Agarwal

Reputation: 444

you can do it simply with help of gin.Context.FileAttachment(path,filename)

go to this respo.

Upvotes: 0

infiniteLearner
infiniteLearner

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

Seaskyways
Seaskyways

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

Related Questions