簡體   English   中英

Golang multipart 持續響應轉發

[英]Golang multipart continuous response forwarding

我有燒瓶蟒蛇的服務器從相機中讀取幀,並把它們放到多的響應,因為它做的在這里

def get_feed():
    while True:
        ret, frame = server.get_frame()
        if not ret:
            try:
                frame = cv2.imread("data/misc/camera_error.jpg")
            except:
                frame = np.zeros(shape=(480, 640, 3), dtype=np.uint8)
        success, buffer = cv2.imencode(".jpg", 
                                       cv2.cvtColor(
                                             frame,
                                             cv2.COLOR_BGR2RGB)
                                       )
        buffer = buffer.tobytes()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + buffer + b'\r\n')

@app.route('/')
def index():
    return Response(get_feed(), mimetype='multipart/x-mixed-replace; boundary=frame')

我有 golang-server 應該接受 GET 請求,將它轉發到燒瓶並將請求轉發給客戶端。

func api_camera_shot(w http.ResponseWriter, r *http.Request) {
    resp, err := http.Get("http://" + *url here*)
    if err != nil {
        fmt.Println(resp)            // debug error
        fmt.Println(err)
        return
    }
    buffer, _ := ioutil.ReadAll(resp.Body)
    for name, values := range resp.Header {
        // Loop over all values for the name.
        for _, value := range values {
            w.Header().Set(name, value)
        }
    }
    _, _ = w.Write(buffer)
}

但它陷入無限循環並且不向客戶端發送任何內容。 據我了解, buffer, _ := ioutil.ReadAll(resp.Body)讀取整個身體,直到燒瓶中的while True仍在運行並且沒有響應。
如何在不卡住的情況下轉發這個連續的多部分請求?

有時,golang 具有我現在使用的代理功能:

    origin, _ := url.Parse("http://" + *url-here*)

    director := func(req *http.Request) {
        req.Header.Add("X-Forwarded-Host", req.Host)
        req.Header.Add("X-Origin-Host", origin.Host)
        req.URL.Scheme = "http"
        req.URL.Host = origin.Host
        req.URL.Path = "/"
    }

    proxy := &httputil.ReverseProxy{Director: director}
    router.Get("/api/camera/*", func(w http.ResponseWriter, r *http.Request) {
        proxy.ServeHTTP(w, r)
    })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM