【问题标题】:Streaming file from Golang backend to Node frontend从 Golang 后端流式传输文件到 Node 前端
【发布时间】: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


【解决方案1】:

我没有专门使用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)
})

【讨论】:

    【解决方案2】:

    可读.pip(可写)

    const express = require('express')
    const http = require("http")
    
    const app = express()
    
    app.get("/path", (req, res, next) => {
        http.get("http://golang/server/url", (res2) => {
            res2.pipe(res)
        })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 2020-07-14
      • 1970-01-01
      • 2015-11-29
      • 2019-07-10
      • 2021-06-30
      • 1970-01-01
      相关资源
      最近更新 更多