node.js - 从 Golang 后端流式传输文件到 Node 前端

标签 node.js file express go streaming

我已经在 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/

相关文章:

javascript - Mongodb findOne - 返回值

javascript - 将缓冲区(图像)转换为文件

每次在c中运行程序时创建一个新文件

javascript - Express 3 的跨 session 问题

node.js - 自定义错误未在 throw 语句或 next() 调用上正确传播

javascript - JS Tape - 等待上一个异步测试完成以进行下一个测试

css - 为什么我的文件结构位置不正确

c++ - 在 C++ 中按行读取大文件

javascript - 从 Express 获取 Google map 地理编码 JSON

reactjs - 为什么我不断收到 500(内部服务器错误)GET http ://localhost:3000/favicon. ico 500(内部服务器错误)?