dtyqeoc70733 2019-01-14 18:10
浏览 525
已采纳

正确设置httputil.ReverseProxy Foward响应流

I have reverse proxies in my main web-server that are dedicated to a certain micro-service and handle forward requests to their appropriate micro-services.

func newTrimPrefixReverseProxy(target *url.URL, prefix string) *httputil.ReverseProxy {
    director := func(req *http.Request) {
        // ... trims prefix from request path and prepends the path of the target url
    }

    return &httputil.ReverseProxy{Director: director}
}

This has worked perfectly for pure JSON responses, but I have ran into issues recently when trying to serve content (stream responses) through the reverse proxy. The means for serving the content is irrelevant, the (video) content is served as intended when the service is accessed directly and not through the reverse proxy.

Serving the content:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    http.ServeContent(w, r, "video.mp4", time.Now().Add(time.Hour*24*365*12*9*-1), videoReadSeeker)
})

Again, the videoReadSeeker and how the content is served is not the issue, the issue is having my response relayed as intended to the requester through the reverse proxy; when accessing the service directly, the video shows up and I can scrub it to my heart's content.

Note that the response for data the content is received (http status, headers), but the content stream in the response body is not.

How can I make sure that the reverse proxy handles streamed responses as intended for the content?

  • 写回答

1条回答 默认 最新

  • doudun1934 2019-01-14 20:49
    关注

    Do you get the same results when using:

    package main
    
    import (
        "log"
        "net/http"
        "net/http/httputil"
        "net/url"
    )
    
    func main() {
        u, err := url.Parse("http://localhost:8080/asdfasdf")
        if err != nil {
            log.Fatal("url.Parse: %v", err)
        }
    
        proxy := httputil.NewSingleHostReverseProxy(u)
    
        log.Printf("Listening at :8081")
        if err := http.ListenAndServe(":8081", proxy); err != nil {
            log.Fatal("ListenAndServe: %v", err)
        }
    }
    

    Ultimately these are the same implementation under the hood, but the director provided here ensures that some of the expected headers exist that you will need for some proxy features to function as expected.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。