英文:
Streaming http response to http ResponseWriter
问题
我想将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)
}
英文:
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)
}
答案1
得分: 4
使用io.Copy
将HTTP请求体的内容流式传输到响应体中。我不确定你为什么持有其他观点。
另外,请直接在问题中发布你的代码,而不是使用外部链接。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论