我已经在 Golang 上设置了后端(封装在 Gin gonic 框架中),前端在 NodeJS 上运行(封装在 Express 框架中)。假设Express是向Golang后台请求一个文件,接收回Express并推送给客户端。
前端 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);
})
});
后端 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)
})
我的问题是:我如何正确地从 Node 向 Golang 请求文件,并将其呈现回客户端,同时保持流式传输文件的可能性(如果有大文件)?
最佳答案
我没有具体使用过 request
库,但本质上您需要如下内容(根据 request
文档判断):
const request = require('request')
// ...
router.get('/my-route', async (req, res) => {
const requestResponse = await request('...')
const binaryFile = Buffer.from(requestResponse.body, 'binary')
res.type(requestResponse.headers('content-type'))
res.end(binaryFile)
})
关于node.js - 从 Golang 后端流式传输文件到 Node 前端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47761810/