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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?