首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

net/http/httptest

  • import "net/http/httptest"
  • 概述
  • 索引
  • 示例

概述

httptest包提供了用于HTTP测试的实用程序。

索引

  • 常量
  • func NewRequest(method, target string, body io.Reader) *http.Request
  • type ResponseRecorder
  • func NewRecorder() *ResponseRecorder
  • func (rw *ResponseRecorder) Flush()
  • func (rw *ResponseRecorder) Header() http.Header
  • func (rw *ResponseRecorder) Result() *http.Response
  • func (rw *ResponseRecorder) Write(buf []byte) (int, error)
  • func (rw *ResponseRecorder) WriteHeader(code int)
  • func (rw *ResponseRecorder) WriteString(str string) (int, error)
  • type Server
  • func NewServer(handler http.Handler) *Server
  • func NewTLSServer(handler http.Handler) *Server
  • func NewUnstartedServer(handler http.Handler) *Server
  • func (s *Server) Certificate() *x509.Certificate
  • func (s *Server) Client() *http.Client
  • func (s *Server) Close()
  • func (s *Server) CloseClientConnections()
  • func (s *Server) Start()
  • func (s *Server) StartTLS()

示例

NewTLSServer ResponseRecorder Server

文件包

常量

如果未在ResponseRecorder上设置明确的DefaultRemoteAddr,则DefaultRemoteAddr是在RemoteAddr中返回的默认远程地址。

代码语言:javascript
复制
const DefaultRemoteAddr = "1.2.3.4"

func NewRequest(显示源文件)

代码语言:javascript
复制
func NewRequest(method, target string, body io.Reader) *http.Request

NewRequest返回一个新的传入服务器请求,适合传递给http.Handler进行测试。

目标是RFC 7230“请求目标”:它可以是路径或绝对URL。如果target是绝对URL,则使用URL中的主机名称。否则,使用“example.com”。

如果目标具有方案“https”,则TLS字段将设置为非零虚拟值。

Request.Proto始终是HTTP/1.1。

一个空的方法意味着“GET”。

提供的body可能是零。如果主体是* bytes.Reader,* strings.Reader或* bytes.Buffer类型,则设置Request.ContentLength。

NewRequest在测试中容易出错,恐慌情况是可以接受的。

要生成客户端HTTP请求而不是服务器请求,请参阅net/http软件包中的NewRequest函数。

type ResponseRecorder(显示源文件)

ResponseRecorder是http.ResponseWriter的一个实现,它记录了其突变,以便在测试中进行后续检查。

代码语言:javascript
复制
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.
        //
        // To get the implicit headers set by the server (such as
        // automatic Content-Type), use 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
}

示例

代码语言:javascript
复制
package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"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, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.StatusCode)
	fmt.Println(resp.Header.Get("Content-Type"))
	fmt.Println(string(body))

}

func NewRecorder(显示源文件)

代码语言:javascript
复制
func NewRecorder() *ResponseRecorder

NewRecorder返回一个初始化的ResponseRecorder。

func (*ResponseRecorder) Flush(显示源文件)

代码语言:javascript
复制
func (rw *ResponseRecorder) Flush()

Flush设置rw.Flushed为true。

func (*ResponseRecorder) Header(显示源文件)

代码语言:javascript
复制
func (rw *ResponseRecorder) Header() http.Header

标题返回响应标题。

func (*ResponseRecorder) Result(显示源文件)

代码语言:javascript
复制
func (rw *ResponseRecorder) Result() *http.Response

结果返回处理程序生成的响应。

返回的Response将至少包含其StatusCode,Header,Body和(可选)Trailer。将来可能会填充更多的字段,因此,调用者不应该将结果进行DeepEqual测试。

Response.Header是第一次写入调用时的头部快照,或者是在调用时(如果处理程序从未写入过的)。

Response.Body保证为非零,并且Body.Read调用保证不会返回除io.EOF以外的任何错误。

只有在处理程序运行完成后才能调用结果。

func (*ResponseRecorder) Write(显示源文件)

代码语言:javascript
复制
func (rw *ResponseRecorder) Write(buf []byte) (int, error)

Write总是成功并写入rw.Body,如果不是零。

func (*ResponseRecorder) WriteHeader(显示源文件)

代码语言:javascript
复制
func (rw *ResponseRecorder) WriteHeader(code int)

WriteHeader设置rw.Code。调用之后,更改rw.Header不会影响rw.HeaderMap。

func (*ResponseRecorder) WriteString(显示源文件)

代码语言:javascript
复制
func (rw *ResponseRecorder) WriteString(str string) (int, error)

WriteString总是成功并写入rw.Body,如果不是零。

服务器是一个HTTP服务器,它侦听本地环回接口上的系统选择端口,用于端到端的HTTP测试。

代码语言:javascript
复制
type Server struct {
        URL      string // base URL of form http://ipaddr:port with no trailing slash
        Listener net.Listener

        // TLS is the optional TLS configuration, populated with a new config
        // after TLS is started. If set on an unstarted server before StartTLS
        // is called, existing fields are copied into the new config.
        TLS *tls.Config

        // Config may be changed after calling NewUnstartedServer and
        // before Start or StartTLS.
        Config *http.Server
        // contains filtered or unexported fields
}

示例

代码语言:javascript
复制
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httptest"
)

func main() {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "Hello, client")
	}))
	defer ts.Close()

	res, err := http.Get(ts.URL)
	if err != nil {
		log.Fatal(err)
	}
	greeting, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s", greeting)
}

func NewServer(显示源文件)

代码语言:javascript
复制
func NewServer(handler http.Handler) *Server

NewServer启动并返回一个新的服务器。调用者在完成时应该调用Close来关闭它。

func NewTLSServer(显示源文件)

代码语言:javascript
复制
func NewTLSServer(handler http.Handler) *Server

NewTLSServer启动并使用TLS返回一个新的服务器。调用者在完成时应该调用Close来关闭它。

示例

代码语言:javascript
复制
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httptest"
)

func main() {
	ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "Hello, client")
	}))
	defer ts.Close()

	client := ts.Client()
	res, err := client.Get(ts.URL)
	if err != nil {
		log.Fatal(err)
	}

	greeting, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s", greeting)
}

func NewUnstartedServer(显示源文件)

代码语言:javascript
复制
func NewUnstartedServer(handler http.Handler) *Server

NewUnstartedServer返回一个新的服务器,但不启动它。

更改配置后,调用者应该调用Start或StartTLS。

调用者在完成时应该调用Close来关闭它。

func (*Server) Certificate(显示源文件)

代码语言:javascript
复制
func (s *Server) Certificate() *x509.Certificate

证书返回服务器使用的证书,如果服务器不使用TLS,则返回nil。

func (*Server) Client(显示源文件)

代码语言:javascript
复制
func (s *Server) Client() *http.Client

客户端返回配置为向服务器发送请求的HTTP客户端。它被配置为信任服务器的TLS测试证书,并关闭Server.Close上的空闲连接。

func (*Server) Close(显示源文件)

代码语言:javascript
复制
func (s *Server) Close()

Close服务器并阻塞,直到此服务器上的所有未完成请求都已完成。

func (*Server) CloseClientConnections(显示源文件)

代码语言:javascript
复制
func (s *Server) CloseClientConnections()

CloseClientConnections关闭所有到测试服务器的开放HTTP连接。

func (*Server) Start(显示源文件)

代码语言:javascript
复制
func (s *Server) Start()

Start从NewUnstartedServer启动服务器。

func (*Server) StartTLS(显示源文件)

代码语言:javascript
复制
func (s *Server) StartTLS()

StartTLS从NewUnstartedServer的服务器上启动TLS。

扫码关注腾讯云开发者

领取腾讯云代金券