Golang: how to read response body of ReverseProxy?

前端 未结 4 699
一整个雨季
一整个雨季 2021-01-31 05:13
package main

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

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


        
4条回答
  •  故里飘歌
    2021-01-31 05:18

    From source code httptest.ResponseRecorder is use for get the response from the handler

    func TestModifyResponseClosesBody(t *testing.T) {
        req, _ := http.NewRequest("GET", "http://foo.tld/", nil)
        req.RemoteAddr = "1.2.3.4:56789"
        closeCheck := new(checkCloser)
        logBuf := new(bytes.Buffer)
        outErr := errors.New("ModifyResponse error")
        rp := &ReverseProxy{
            Director: func(req *http.Request) {},
            Transport: &staticTransport{&http.Response{
                StatusCode: 200,
                Body:       closeCheck,
            }},
            ErrorLog: log.New(logBuf, "", 0),
            ModifyResponse: func(*http.Response) error {
                return outErr
            },
        }
        rec := httptest.NewRecorder()
        rp.ServeHTTP(rec, req)
        res := rec.Result()
        if g, e := res.StatusCode, http.StatusBadGateway; g != e {
            t.Errorf("got res.StatusCode %d; expected %d", g, e)
        }
        if !closeCheck.closed {
            t.Errorf("body should have been closed")
        }
        if g, e := logBuf.String(), outErr.Error(); !strings.Contains(g, e) {
            t.Errorf("ErrorLog %q does not contain %q", g, e)
        }
    }
    

提交回复
热议问题