当前位置: 首页>>代码示例>>Golang>>正文


Golang ResponseRecorder.Body方法代码示例

本文整理汇总了Golang中net/http/httptest.ResponseRecorder.Body方法的典型用法代码示例。如果您正苦于以下问题:Golang ResponseRecorder.Body方法的具体用法?Golang ResponseRecorder.Body怎么用?Golang ResponseRecorder.Body使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net/http/httptest.ResponseRecorder的用法示例。


在下文中一共展示了ResponseRecorder.Body方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: DoRequest

// DoRequest invokes a request on the given handler with the given
// parameters.
func DoRequest(c *gc.C, p DoRequestParams) *httptest.ResponseRecorder {
	if p.Method == "" {
		p.Method = "GET"
	}
	if p.Do == nil {
		p.Do = http.DefaultClient.Do
	}
	srv := httptest.NewServer(p.Handler)
	defer srv.Close()

	if p.JSONBody != nil {
		data, err := json.Marshal(p.JSONBody)
		c.Assert(err, jc.ErrorIsNil)
		p.Body = bytes.NewReader(data)
	}
	// Note: we avoid NewRequest's odious reader wrapping by using
	// a custom nopCloser function.
	req, err := http.NewRequest(p.Method, srv.URL+p.URL, nopCloser(p.Body))
	c.Assert(err, jc.ErrorIsNil)
	if p.JSONBody != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	for key, val := range p.Header {
		req.Header[key] = val
	}
	if p.ContentLength != 0 {
		req.ContentLength = p.ContentLength
	} else {
		req.ContentLength = bodyContentLength(p.Body)
	}
	if p.Username != "" || p.Password != "" {
		req.SetBasicAuth(p.Username, p.Password)
	}
	for _, cookie := range p.Cookies {
		req.AddCookie(cookie)
	}
	resp, err := p.Do(req)
	if p.ExpectError != "" {
		c.Assert(err, gc.ErrorMatches, p.ExpectError)
		return nil
	}
	c.Assert(err, jc.ErrorIsNil)
	defer resp.Body.Close()

	// TODO(rog) don't return a ResponseRecorder because we're not actually
	// using httptest.NewRecorder ?
	var rec httptest.ResponseRecorder
	rec.HeaderMap = resp.Header
	rec.Code = resp.StatusCode
	rec.Body = new(bytes.Buffer)
	_, err = io.Copy(rec.Body, resp.Body)
	c.Assert(err, jc.ErrorIsNil)
	return &rec
}
开发者ID:claudiu-coblis,项目名称:testing,代码行数:56,代码来源:http.go

示例2: DoRequest

// DoRequest is the same as Do except that it returns
// an httptest.ResponseRecorder instead of an http.Response.
// This function exists for backward compatibility reasons.
func DoRequest(c *gc.C, p DoRequestParams) *httptest.ResponseRecorder {
	resp := Do(c, p)
	if p.ExpectError != "" {
		return nil
	}
	defer resp.Body.Close()
	var rec httptest.ResponseRecorder
	rec.HeaderMap = resp.Header
	rec.Code = resp.StatusCode
	rec.Body = new(bytes.Buffer)
	_, err := io.Copy(rec.Body, resp.Body)
	c.Assert(err, jc.ErrorIsNil)
	return &rec
}
开发者ID:cmars,项目名称:oo,代码行数:17,代码来源:http.go


注:本文中的net/http/httptest.ResponseRecorder.Body方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。