我在flask-python上有一个服务器,它从相机读取帧并将它们放入多部分响应中,就像这里一样:
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'--framern'
b'Content-Type: image/jpegrnrn' + buffer + b'rn')
@app.route('/')
def index():
return Response(get_feed(), mimetype='multipart/x-mixed-replace; boundary=frame')
我有golang-server,它应该接受GET请求,将其转发给flask,并将请求转发给客户端。
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)
})