dsfdsf21312 2017-12-11 21:35
浏览 531

将文件从Golang后端流传输到Node前端

I have set up a backend on Golang (wrapped in Gin gonic framework) and the frontend is run on NodeJS (wrapped in Express framework). Assume Express is to make a request to Golang backend to request a file, receive it back to Express and push to the client.

Frontend 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);  

  })

});

Backend 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)

})

My question is: How do I properly request a file from Node to Golang, and render it back to the client, keeping the possibility of streaming file (if there would be a large file)?

  • 写回答

1条回答 默认 最新

  • dongzhan1383 2017-12-12 20:15
    关注

    I haven't used the request library specifically, but essentially you need something like the following (judging from the request documentation):

    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)
    })
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)