1 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個(gè)贊
沒有一種方法可以替代 Do 方法,但是有一種方法可以實(shí)現(xiàn)您的目標(biāo)。
創(chuàng)建一個(gè)返回任意響應(yīng)主體的往返類型:
type respondWithReader struct{ body io.Reader }
func (rr respondWithReader) RoundTrip(req *http.Request) (*http.Response, error) {
return &http.Response{
Proto: "HTTP/1.0",
ProtoMajor: 1,
Header: make(http.Header),
Close: true,
Body: ioutil.NopCloser(rr.body),
}, nil
}
創(chuàng)建一個(gè)失敗的 io.Reader:
var errReadFail = errors.New("blah!")
type failReader int
func (failReader) Read([]byte) (int, error) {
return 0, errReadFail
}
將 stock 客戶端與上面的傳輸和閱讀器一起使用:
c := http.Client{Transport: respondWithReader{body: failReader(0)}}
resp, err := c.Get("http://whatever.com")
if err != nil {
t.Error(err)
}
defer resp.Body.Close()
// ReadAll returns errReadFail
_, err = ioutil.ReadAll(resp.Body)
if err != errReadFail {
t.Errorf("got err %v, expect %v", err, errReadFail)
}
- 1 回答
- 0 關(guān)注
- 106 瀏覽
添加回答
舉報(bào)