doutang1946
2015-07-21 09:43
浏览 296
已采纳

Golang:如何读取ReverseProxy的响应主体?

package main

import (
    "net/http"
    "net/http/httputil"
    "net/url"
)

func main() {
    target := &url.URL{Scheme: "http", Host: "www.google.com"}
    proxy := httputil.NewSingleHostReverseProxy(target)

    http.Handle("/google", proxy)
    http.ListenAndServe(":8099", nil)
}

Reverse Proxy is works. How can I get the response body?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanpai1920 2015-07-21 10:48
    已采纳

    httputil.ReverseProxy has a Transport field. You can use it to modify the response. For example:

    type transport struct {
        http.RoundTripper
    }
    
    func (t *transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
        resp, err = t.RoundTripper.RoundTrip(req)
        if err != nil {
            return nil, err
        }
        b, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            return nil, err
        }
        err = resp.Body.Close()
        if err != nil {
            return nil, err
        }
        b = bytes.Replace(b, []byte("server"), []byte("schmerver"), -1)
        body := ioutil.NopCloser(bytes.NewReader(b))
        resp.Body = body
        resp.ContentLength = int64(len(b))
        resp.Header.Set("Content-Length", strconv.Itoa(len(b)))
        return resp, nil
    }
    
    // ...
    proxy := httputil.NewSingleHostReverseProxy(target)
    proxy.Transport = &transport{http.DefaultTransport}
    

    Playground example of the whole thing: http://play.golang.org/p/b0S5CbCMrI.

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题