Reputation: 307
I want to stream an HTTP GET response to HTTP responsewriter. I have searched for the solution online and finally used io.Copy for that. But it's not streaming, instead, it is downloading the entire get response and then passing to HTTP responsewriter. I'm stuck with this problem for 2 days. Help me out if you know. Below is the sample code
package main
import (
"fmt"
"io"
"net/http"
"time"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.Path("/test").HandlerFunc(Stream).Methods("GET")
srv := &http.Server{
Addr: ":4000",
Handler: router,
ReadTimeout: 30 * time.Minute,
WriteTimeout: 30 * time.Minute,
IdleTimeout: 60 * time.Minute,
}
srv.SetKeepAlivesEnabled(true)
fmt.Println(srv.ListenAndServe())
}
// Stream .
func Stream(w http.ResponseWriter, r *http.Request) {
req, err := http.NewRequest("GET", "https://lh3.googleusercontent.com/k3ysodYwXwhm7ThrM_-zbqhETk8CUfMd5vuG9RbjBKrKAKQaUfZpiRRDg8ZEaT-WfsDkRfS_cheTM4JvT3TEoNEPF4gzofkq0Y6ykGVT_WhG4hXG-nAdkpeyeY1kMysqBWdS5YDGIPY=d", nil)
if err != nil {
return
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
w.Header().Set("content-type", "video/mp4")
w.WriteHeader(206)
w.Header().Set("Status", "206")
i, err := io.Copy(w, resp.Body)
fmt.Println(i, err)
}
Upvotes: 0
Views: 3771
Reputation: 1584
Using io.Copy
is streaming the content of the http request body to the response body. I'm not sure why you think otherwise.
Also please post your code directly in the question rather than in an external link.
Upvotes: 4