GO语言"net/http/httptest"包中"ResponseRecorder"类型的用法及代码示例。
ResponseRecorder 是 http ResponseWriter 的一个实现,它记录其突变以供以后在测试中检查。
用法:
type ResponseRecorder struct {
// Code is the HTTP response code set by WriteHeader.
//
// Note that if a Handler never calls WriteHeader or Write,
// this might end up being 0, rather than the implicit
// http.StatusOK.To get the implicit value, use the Result
// method.
Code int
// HeaderMap contains the headers explicitly set by the Handler.
// It is an internal detail.
//
// Deprecated: HeaderMap exists for historical compatibility
// and should not be used.To access the headers returned by a handler,
// use the Response.Header map as returned by the Result method.
HeaderMap http.Header
// Body is the buffer to which the Handler's Write calls are sent.
// If nil, the Writes are silently discarded.
Body *bytes.Buffer
// Flushed is whether the Handler called Flush.
Flushed bool
// contains filtered or unexported fields
}
例子:
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
)
func main() {
handler := func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "<html><body>Hello World!</body></html>")
}
req := httptest.NewRequest("GET", "http://example.com/foo", nil)
w := httptest.NewRecorder()
handler(w, req)
resp := w.Result()
body, _ := io.ReadAll(resp.Body)
fmt.Println(resp.StatusCode)
fmt.Println(resp.Header.Get("Content-Type"))
fmt.Println(string(body))
}
输出:
200 text/html; charset=utf-8 <html><body>Hello World!</body></html>
相关用法
- GO ResponseWriter用法及代码示例
- GO Regexp.FindString用法及代码示例
- GO Regexp.FindAllIndex用法及代码示例
- GO ReverseBytes64用法及代码示例
- GO ReverseBytes16用法及代码示例
- GO Regexp.ReplaceAllLiteralString用法及代码示例
- GO Regexp.FindStringSubmatch用法及代码示例
- GO Regexp.FindAllString用法及代码示例
- GO ReadMessage用法及代码示例
- GO Regexp.ExpandString用法及代码示例
- GO Regexp.FindAllStringSubmatch用法及代码示例
- GO Reverse用法及代码示例
- GO Read用法及代码示例
- GO Rel用法及代码示例
- GO Regexp.SubexpIndex用法及代码示例
- GO Regexp.Match用法及代码示例
- GO Remainder用法及代码示例
- GO Regexp.Longest用法及代码示例
- GO Replace用法及代码示例
- GO ReadFile用法及代码示例
注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 ResponseRecorder。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。