【发布时间】:2021-04-25 15:49:02
【问题描述】:
我在 Golang 上设置了一个后端(包装在 Gin gonic 框架中),前端运行在 NodeJS 上(包装在 Express 框架中)。假设 Express 是向 Golang 后端发出请求请求文件,将其接收回 Express 并推送到客户端。
前端节点:
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 请求文件,并将其渲染回客户端,保持流文件的可能性(如果有大文件)?
【问题讨论】:
-
如果您只需要一个文件,http.FileServer() 将为您完成大部分工作。从节点请求它作为任何其他文件。
标签: node.js file express go streaming