非常教程

Go参考手册

net/http

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

文件包

httptest.go recorder.go server.go

常量

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

const DefaultRemoteAddr = "1.2.3.4"

func NewRequest(显示源文件)

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的一个实现,它记录了其突变,以便在测试中进行后续检查。

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
}

示例

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(显示源文件)

func NewRecorder() *ResponseRecorder

NewRecorder返回一个初始化的ResponseRecorder。

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

func (rw *ResponseRecorder) Flush()

Flush设置rw.Flushed为true。

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

func (rw *ResponseRecorder) Header() http.Header

标题返回响应标题。

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

func (rw *ResponseRecorder) Result() *http.Response

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

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

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

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

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

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

func (rw *ResponseRecorder) Write(buf []byte) (int, error)

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

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

func (rw *ResponseRecorder) WriteHeader(code int)

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

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

func (rw *ResponseRecorder) WriteString(str string) (int, error)

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

type Server(显示源文件)

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

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
}

示例

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(显示源文件)

func NewServer(handler http.Handler) *Server

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

func NewTLSServer(显示源文件)

func NewTLSServer(handler http.Handler) *Server

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

示例

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(显示源文件)

func NewUnstartedServer(handler http.Handler) *Server

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

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

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

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

func (s *Server) Certificate() *x509.Certificate

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

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

func (s *Server) Client() *http.Client

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

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

func (s *Server) Close()

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

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

func (s *Server) CloseClientConnections()

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

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

func (s *Server) Start()

Start从NewUnstartedServer启动服务器。

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

func (s *Server) StartTLS()

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

Go

Go 是一种编译型语言,它结合了解释型语言的游刃有余,动态类型语言的开发效率,以及静态类型的安全性。它也打算成为现代的,支持网络与多核计算的语言。要满足这些目标,需要解决一些语言上的问题:一个富有表达能力但轻量级的类型系统,并发与垃圾回收机制,严格的依赖规范等等。这些无法通过库或工具解决好,因此Go也就应运而生了。

主页 https://golang.org/
源码 https://go.googlesource.com/go
发布版本 1.9.2

Go目录

1.档案 | archive
2.缓冲区 | bufio
3.内置 | builtin
4.字节 | bytes
5.压缩 | compress
6.容器 | container
7.上下文 | context
8.加密 | crypto
9.数据库 | database
10.调试 | debug
11.编码 | encoding
12.错误 | errors
13. expvar
14.flag
15. fmt
16. go
17.散列 | hash
18.html
19.图像 | image
20.索引 | index
21.io
22.日志 | log
23.数学 | math
24. math/big
25.math/bits
26.math/cmplx
27.math/rand
28.拟态 | mime
29.net
30.net/http
31. net/mail
32. net/rpc
33.net/smtp
34. net/textproto
35. net/url
36.os
37.路径 | path
38.插件 | plugin
39.反射 | reflect
40.正则表达式 | regexp
41.运行时 | runtime
42.排序算法 | sort
43.转换 | strconv
44.字符串 | strings
45.同步 | sync
46.系统调用 | syscall
47.测试 | testing
48.文本 | text
49.时间戳 | time
50.unicode
51.不安全性 | unsafe
52.Go 语言数据类型
53.Go 语言基础语法
54.Go 语言结构
55.Go 语言 select 语句
56.Go 语言 switch 语句
57.Go 语言 if 语句嵌套
58.Go 语言 if…else 语句
59.Go 语言 if 语句
60.Go 语言运算符
61.Go 语言常量
62.Go 语言函数闭包
63.Go 语言函数作为实参
64.Go 语言函数引用传递值
65.Go 语言函数值传递值
66.Go 语言函数
67.Go 语言 goto 语句
68.Go 语言 continue 语句
69.Go 语言 break 语句
70.Go 语言循环嵌套
71.Go 语言 for 循环
72.Go 语言结构体
73.Go 语言指针作为函数参数
74.Go 语言指向指针的指针
75.Go 语言指针数组
76.Go 语言指针
77.Go 语言向函数传递数组
78.Go 语言多维数组
79.Go 语言变量作用域
80.Go 语言函数方法
81.Go 错误处理
82.Go 语言接口
83.Go 语言类型转换
84.Go 语言递归函数
85.Go 语言Map(集合)
86.Go 语言范围(Range)
87.Go 语言切片(Slice)
88.Go 并发
89.Go fmt.Sprintf 格式化字符串