Reputation: 129
I have a golang backend with gin. Its supposed to work as a proxy for a ftp server that contains audiofiles. So my client should be able to call the endpoint /download/filepath the Golang application is then supposed to fetch the file from a ftp server and return it as a file(no stream).
My current solution is to read the file from the ftp as []byte and temporarily write it to disk with ioutil.TempFile() and return that file with ctx.File().
If possible I would like to skip the step where I'm creating a tempfile. Is that possible? Perhaps theres a way to proxy the call and directly connect the http call to the ftp call?
Note I don't control the client application so I can't change it.
Upvotes: 11
Views: 13333
Reputation: 101
Gin framework, to serve binary files to client then the browser automatically downloads the file when the user hits the API, and the server doesn't need to save the file (There isn't static file), then use this method c.Data. Where the data type of the third parameter is []byte. Here is the example code.
func DownloadFile(c *gin.Context) {
byteFile, err := ioutil.ReadFile("./file.txt")
if err != nil {
fmt.Println(err)
}
c.Header("Content-Disposition", "attachment; filename=file-name.txt")
c.Data(http.StatusOK, "application/octet-stream", byteFile)
}
Upvotes: 10
Reputation: 106
Use Context.Data to write a []byte
as the response.
You can also use Context.DataFromReader to copy directly from the FTP response to the HTTP response.
HTTP responses are a stream of bytes. There's no way to get around that.
Upvotes: 9
Reputation: 2262
You can write to the ResponseWriter
as you are reading the file. It works just like using http.ResponseWriter
.
import "io"
//...
io.Copy(ctx.ResponseWriter, ftpReader)
Upvotes: 1