I have set up a backend on Golang (wrapped in Gin gonic framework) and the frontend is run on NodeJS (wrapped in Express framework). Assume Express is to make a request to Golang backend to request a file, receive it back to Express and push to the client.
Frontend Node:
var request = require('request');
router.get('/testfile', function (req, res, next) {
// URL to Golang backend server
var filepath = 'http://127.0.0.1:8000/testfile';
request(filepath, function (error, response, body) {
// This is incorrect, as it's just rendering the body to the client as text
res.send(body);
})
});
Backend Golang:
r.GET("/testfile", func(c *gin.Context) {
url := "http://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png"
timeout := time.Duration(5) * time.Second
transport := &http.Transport{
ResponseHeaderTimeout: timeout,
Dial: func(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, timeout)
},
DisableKeepAlives: true,
}
client := &http.Client{
Transport: transport,
}
resp, err := client.Get(url)
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
c.Writer.Header().Set("Content-Disposition", "attachment; filename=Wiki.png")
c.Writer.Header().Set("Content-Type", c.Request.Header.Get("Content-Type"))
c.Writer.Header().Set("Content-Length", c.Request.Header.Get("Content-Length"))
//stream the body to the client without fully loading it into memory
io.Copy(c.Writer, resp.Body)
})
My question is: How do I properly request a file from Node to Golang, and render it back to the client, keeping the possibility of streaming file (if there would be a large file)?