2017-12-11 3 views
0

노드한다. 익스프레스가 Golang 백엔드에 요청하여 파일을 요청한 다음 익스프레스로 다시 보내 클라이언트로 푸시한다고 가정합니다.스트리밍 파일은 내가 (진 gonic 프레임 워크에 싸여) <strong>Golang</strong>에 백엔드를 설정하고 프론트 엔드는 <strong>NodeJS (익스프레스 프레임 워크에 싸여)</strong>에서 실행되는 프론트 엔드

프런트 엔드 노드 :

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) 

}) 

내 질문은 : 가 어떻게 제대로 Golang에 노드에서 파일을 요청 않으며, 위로를 렌더링 클라이언트는 스트리밍 파일의 가능성을 유지합니다 (큰 파일이있을 경우)?

+1

당신은 그냥 파일이 필요하면 [http.FileServer()] (https://golang.org/pkg/net/http/#FileServer)는 나중에 대부분의 작업을 수행합니다. 노드에서 다른 파일로 요청하십시오. – biosckon

답변

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) 
}) 
관련 문제