我想将 HTTP GET 响应流式传输到 HTTP responsewriter。我在网上搜索了解决方案,最后使用了 io.Copy 。但它不是流式传输,而是下载整个 get 响应,然后传递给 HTTP responsewriter。我被这个问题困扰了2天。如果你知道,请帮助我。下面是示例代码
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)
}