doukang7486 2019-08-01 21:47
浏览 66

在反向代理中多次重复http.Request

I'm implementing a http.RoundTripper in Go, and as part of httputil.ReverseProxy implementation.

I need to buffer an incoming request, and repeat it several times, depending on the response I get from the backend. To do this, I use request.Write and http.ReadRequest. (I am actually not sure if this is a good idea, if there are any better ways, I'm interested.)

After deserializing request from []byte with http.ReadRequest and repeat it using the http.DefaultTransport’s roundtripper, I get this printed in my stderr:

2019/08/01 14:35:51 http: proxy error: unsupported protocol scheme ""

So it looks like for some reason I need to set req.URL again after deserializing to make it work.

Here's roughly how my code looks like:

func (s *myServer) RoundTrip(origReq *http.Request) (*http.Response, error) {
    var b bytes.Buffer
    if err := origReq.Write(&b); err != nil {
        return nil, errors.Wrap(err,"failed to buffer request")
    }
    for retries := 0; retries < s.maxRetries; retries++{
        req, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(b.Bytes()))) // probably can be simplified
        if err != nil {
            return nil, errors.Wrap(err,"failed to un-buffer request")
        }
        req.URL = origReq.URL // <-- why is this necessary?

        resp, err := http.DefaultTransport.RoundTrip(req)
        if err != nil {
            return resp, err
        }
        if needRepeat(resp) {
            continue
        }
        return resp, nil
    }
}
  • 写回答

1条回答 默认 最新

  • du6029076877 2019-08-02 05:05
    关注

    ReadRequest reads a server request. Request.Write writes a client request. See the Request.URL documentation for how the Request.URL is handled differently in client and server requests.

    Given that ReadRequest and Request.Write are not inverses of each other, a better approach is to copy the request body before the loop and create a new request on each iteration using data from the original request and the copied request body.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大