0

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)
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

4

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.

Peter
  • 29,454
  • 5
  • 48
  • 60
aureliar
  • 1,476
  • 4
  • 16
  • If I run the code above and open localhost:4000/test, I'm not able to watch the video. Request is still in pending. Here is the reference screenshot - https://imgur.com/a/VYg5jPW – Sai Rahul Akarapu May 21 '21 at 11:53
  • 1
    This is because the **browser** is waiting for all the video to be downloaded. But the server is streaming it. Now if you want to display partially downloaded video in the browser this is an other problem. – aureliar May 21 '21 at 12:44