dongming8867 2014-01-21 23:07
浏览 546
已采纳

如何从NewSingleHostReverseProxy读取响应

I've created a reverse proxy like this:

func ProxyFunc(w http.ResponseWriter, r *http.Request) {
    u, err := url.Parse("http://mynetworkserverhere:8957/some/path/here/")
    if err == nil {
        proxy := httputil.NewSingleHostReverseProxy(u)
        proxy.ServeHTTP(w, r)
        //????

    } else {
        w.Write([]byte(err.Error()))
    }
}

And invoke it from main:

func main() {
   log.Printf("Starting...")
   http.HandleFunc("/", ProxyFunc)
   log.Fatal(http.ListenAndServe(":6060", nil))
}

And it works as expected from the client side, but I'd like to read the response from the proxy, how can I do that?

  • 写回答

1条回答 默认 最新

  • duanlei1957 2014-01-22 02:09
    关注

    The net/http package is really flexible. You can replace the default Transport of the ReverseProxy with your own, which just uses the DefaultTransport. Then you can intercept the RoundTrip call and do whatever you'd like.

    package main
    
    import (
        "log"
        "net/http"
        "net/http/httputil"
        "net/url"
    )
    
    func main() {
        log.Printf("Starting...")
        http.HandleFunc("/", someFunc)
        log.Fatal(http.ListenAndServe(":6060", nil))
    }
    
    func someFunc(w http.ResponseWriter, r *http.Request) {
    
        // change the request host to match the target
        r.Host = "you.host.here:port"
        u, _ := url.Parse("http://you.host.here:port/some/path/")
        proxy := httputil.NewSingleHostReverseProxy(u)
        // You can optionally capture/wrap the transport if that's necessary (for
        // instance, if the transport has been replaced by middleware). Example:
        // proxy.Transport = &myTransport{proxy.Transport}
        proxy.Transport = &myTransport{}
    
        proxy.ServeHTTP(w, r)
    }
    
    type myTransport struct {
        // Uncomment this if you want to capture the transport
        // CapturedTransport http.RoundTripper
    }
    
    func (t *myTransport) RoundTrip(request *http.Request) (*http.Response, error) {
        response, err := http.DefaultTransport.RoundTrip(request)
        // or, if you captured the transport
        // response, err := t.CapturedTransport.RoundTrip(request)
    
        // The httputil package provides a DumpResponse() func that will copy the
        // contents of the body into a []byte and return it. It also wraps it in an
        // ioutil.NopCloser and sets up the response to be passed on to the client.
        body, err := httputil.DumpResponse(response, true)
        if err != nil {
            // copying the response body did not work
            return nil, err
        }
    
        // You may want to check the Content-Type header to decide how to deal with
        // the body. In this case, we're assuming it's text.
        log.Print(string(body))
    
        return response, err
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集