从Golang后端到Node前端的流文件

时间:2017-12-11 21:35:35

标签: node.js file express go streaming

我已经在 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请求文件,并将其渲染回客户端,保留流文件的可能性(如果有大文件)?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

可读.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)
    })
})