Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Piping http.Response to http.ResponseWriter

Tags:

go

I'm trying to pipe a file that I receive from an API back to the user without having to store it all in memory.

I've come across different concepts/ideas across my search, such as io.Copy, io.Pipe(), etc. I'm not sure which one is the correct solution.

For example, io.Pipe() seems like it's for if someone is creating a new reader and writer on the spot, not ones that already exist.

like image 708
John Avatar asked Mar 06 '15 02:03

John


1 Answers

io.Copy is the way to go for that, something along the lines of:

func pipeReq(rw http.ResponseWriter, req *http.Request) {
    resp, err := http.Get(".....")
    if err != nil{
        //handle the error
        return
    }
    rw.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
    rw.Header().Set("Content-Length", resp.Header.Get("Content-Length"))
    io.Copy(rw, resp.Body)
    resp.Body.Close()

}

//edit: misread the question, fixed the code now.

like image 118
OneOfOne Avatar answered Oct 31 '22 08:10

OneOfOne