非常教程

Go参考手册

net/http

net/http/httputil

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

概述

软件包httputil提供HTTP实用程序功能,补充了net/http软件包中较常见的功能。

索引

  • 变量
  • func DumpRequest(req *http.Request, body bool) ([]byte, error)
  • func DumpRequestOut(req *http.Request, body bool) ([]byte, error)
  • func DumpResponse(resp *http.Response, body bool) ([]byte, error)
  • func NewChunkedReader(r io.Reader) io.Reader
  • func NewChunkedWriter(w io.Writer) io.WriteCloser
  • type BufferPool
  • type ClientConn
  • func NewClientConn(c net.Conn, r *bufio.Reader) *ClientConn
  • func NewProxyClientConn(c net.Conn, r *bufio.Reader) *ClientConn
  • func (cc *ClientConn) Close() error
  • func (cc *ClientConn) Do(req *http.Request) (*http.Response, error)
  • func (cc *ClientConn) Hijack() (c net.Conn, r *bufio.Reader)
  • func (cc *ClientConn) Pending() int
  • func (cc *ClientConn) Read(req *http.Request) (resp *http.Response, err error)
  • func (cc *ClientConn) Write(req *http.Request) error
  • type ReverseProxy
  • func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy
  • func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request)
  • type ServerConn
  • func NewServerConn(c net.Conn, r *bufio.Reader) *ServerConn
  • func (sc *ServerConn) Close() error
  • func (sc *ServerConn) Hijack() (net.Conn, *bufio.Reader)
  • func (sc *ServerConn) Pending() int
  • func (sc *ServerConn) Read() (*http.Request, error)
  • func (sc *ServerConn) Write(req *http.Request, resp *http.Response) error

示例

DumpRequest DumpRequestOut DumpResponse ReverseProxy

文件包

dump.go httputil.go persist.go reverseproxy.go

变量

var (
        // Deprecated: No longer used.
        ErrPersistEOF = &http.ProtocolError{ErrorString: "persistent connection closed"}

        // Deprecated: No longer used.
        ErrClosed = &http.ProtocolError{ErrorString: "connection closed by user"}

        // Deprecated: No longer used.
        ErrPipeline = &http.ProtocolError{ErrorString: "pipeline error"}
)

使用太长的行读取格式不正确的分块数据时,会返回ErrLineTooLong。

var ErrLineTooLong = internal.ErrLineTooLong

func DumpRequest(显示源文件)

func DumpRequest(req *http.Request, body bool) ([]byte, error)

DumpRequest以HTTP/1.x线表示形式返回给定的请求。它只能被服务器用来调试客户端请求。返回的表示只是一个近似值; 解析为http.Request时,初始请求的某些细节会丢失。特别是头字段名称的顺序和大小写会丢失。多值头中值的顺序保持不变。HTTP/2请求以HTTP/1.x形式转储,而不是以其原始二进制表示。

如果body正确,DumpRequest也返回正文。为此,它使用req.Body,然后用一个新的产生相同字节的io.ReadCloser来替换它。如果DumpRequest返回错误,则req的状态是未定义的。

http.Request.Write的文档详细说明了哪些req字段包含在转储中。

示例

package main

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

func main() {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		dump, err := httputil.DumpRequest(r, true)
		if err != nil {
			http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
			return
		}

		fmt.Fprintf(w, "%q", dump)
	}))
	defer ts.Close()

	const body = "Go is a general-purpose language designed with systems programming in mind."
	req, err := http.NewRequest("POST", ts.URL, strings.NewReader(body))
	if err != nil {
		log.Fatal(err)
	}
	req.Host = "www.example.org"
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s", b)

}

func DumpRequestOut(显示源文件)

func DumpRequestOut(req *http.Request, body bool) ([]byte, error)

DumpRequestOut就像DumpRequest,但是用于传出客户端请求。它包括标准http.Transport添加的任何标题,例如User-Agent。

示例

package main

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"strings"
)

func main() {
	const body = "Go is a general-purpose language designed with systems programming in mind."
	req, err := http.NewRequest("PUT", "http://www.example.org", strings.NewReader(body))
	if err != nil {
		log.Fatal(err)
	}

	dump, err := httputil.DumpRequestOut(req, true)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%q", dump)

}

func DumpResponse(显示源文件)

func DumpResponse(resp *http.Response, body bool) ([]byte, error)

DumpResponse与DumpRequest类似,但会转储响应。

示例

package main

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"net/http/httputil"
)

func main() {
	const body = "Go is a general-purpose language designed with systems programming in mind."
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Date", "Wed, 19 Jul 1972 19:00:00 GMT")
		fmt.Fprintln(w, body)
	}))
	defer ts.Close()

	resp, err := http.Get(ts.URL)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	dump, err := httputil.DumpResponse(resp, true)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%q", dump)

}

func NewChunkedReader(显示源文件)

func NewChunkedReader(r io.Reader) io.Reader

NewChunkedReader返回一个新的chunkedReader,它在返回之前将从r读出的数据转换成HTTP“chunked”格式。chunkedReader在读取最后的0长度块时返回io.EOF。

普通应用程序不需要NewChunkedReader。在阅读响应主体时,http包会自动解码分块。

func NewChunkedWriter(显示源文件)

func NewChunkedWriter(w io.Writer) io.WriteCloser

NewChunkedWriter返回一个新的chunkedWriter,在写入w之前将写入转换为HTTP“分块”格式。关闭返回的chunkedWriter将发送标记流结束的最终0长度块。

普通应用程序不需要NewChunkedWriter。如果处理程序未设置Content-Length标头,则http包会自动添加分块。在处理程序中使用NewChunkedWriter会导致双重组块或使用Content-Length长度分块,这两者都是错误的。

type BufferPool(显示源文件)

BufferPool是一个获取和返回io.CopyBuffer使用的临时字节片的接口。

type BufferPool interface {
        Get() []byte
        Put([]byte)
}

type ClientConn(显示源文件)

ClientConn是Go早期HTTP实现的产物。它是Go的当前HTTP堆栈的低级,旧的和未使用的。我们应该在Go 1之前删除它。

Deprecated:在net/http包中使用客户端或传输。

type ClientConn struct {
        // contains filtered or unexported fields
}

func NewClientConn(显示源文件)

func NewClientConn(c net.Conn, r *bufio.Reader) *ClientConn

NewClientConn是Go早期HTTP实现的一个工件。它是Go的当前HTTP堆栈的低级,旧的和未使用的。我们应该在Go 1之前删除它。

Deprecated:使用客户端或传输net/http包代替。

func NewProxyClientConn(显示源文件)

func NewProxyClientConn(c net.Conn, r *bufio.Reader) *ClientConn

NewProxyClientConn是Go早期HTTP实现的工件。它是Go的当前HTTP堆栈的低级,旧的和未使用的。我们应该在Go 1之前删除它。

Deprecated:使用客户端或传输net/http包代替。

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

func (cc *ClientConn) Close() error

Close调用Hijack,然后关闭底层连接。

func (*ClientConn) Do(显示源文件)

func (cc *ClientConn) Do(req *http.Request) (*http.Response, error)

Do是写请求并读取响应的便利方法。

func (*ClientConn) Hijack(显示源文件)

func (cc *ClientConn) Hijack() (c net.Conn, r *bufio.Reader)

劫持分离ClientConn并返回底层连接以及可能留下数据的读取端bufio。可以在用户或Read之前调用劫持标志保持活动逻辑的结束。在读取或写入过程中,用户不应该调用劫持。

func (*ClientConn) Pending(显示源文件)

func (cc *ClientConn) Pending() int

Pending返回已经在连接上发送的未应答请求的数量。

func (*ClientConn) Read(显示源文件)

func (cc *ClientConn) Read(req *http.Request) (resp *http.Response, err error)

Read从电线读取下一个响应。有效的响应可能会与ErrPersistEOF一起返回,这意味着远程请求这是最后一次请求服务。Read可以与Write同时调用,但不能与另一个Read一起调用。

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

func (cc *ClientConn) Write(req *http.Request) error

Write写入请求。如果连接已经以HTTP Keepalive意义关闭,则返回ErrPersistEOF错误。如果req.Close等于true,则在此请求和对端服务器被通知后,保持连接在逻辑上关闭。ErrUnexpectedEOF指示远程关闭了底层TCP连接,通常认为该连接处于优雅关闭状态。

type ReverseProxy(显示源文件)

ReverseProxy是一个HTTP处理程序,它接收传入的请求并将其发送到另一个服务器,将响应代理回客户端。

type ReverseProxy struct {
        // Director must be a function which modifies
        // the request into a new request to be sent
        // using Transport. Its response is then copied
        // back to the original client unmodified.
        // Director must not access the provided Request
        // after returning.
        Director func(*http.Request)

        // The transport used to perform proxy requests.
        // If nil, http.DefaultTransport is used.
        Transport http.RoundTripper

        // FlushInterval specifies the flush interval
        // to flush to the client while copying the
        // response body.
        // If zero, no periodic flushing is done.
        FlushInterval time.Duration

        // ErrorLog specifies an optional logger for errors
        // that occur when attempting to proxy the request.
        // If nil, logging goes to os.Stderr via the log package's
        // standard logger.
        ErrorLog *log.Logger

        // BufferPool optionally specifies a buffer pool to
        // get byte slices for use by io.CopyBuffer when
        // copying HTTP response bodies.
        BufferPool BufferPool

        // ModifyResponse is an optional function that
        // modifies the Response from the backend.
        // If it returns an error, the proxy returns a StatusBadGateway error.
        ModifyResponse func(*http.Response) error
}

示例

package main

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

func main() {
	backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "this call was relayed by the reverse proxy")
	}))
	defer backendServer.Close()

	rpURL, err := url.Parse(backendServer.URL)
	if err != nil {
		log.Fatal(err)
	}
	frontendProxy := httptest.NewServer(httputil.NewSingleHostReverseProxy(rpURL))
	defer frontendProxy.Close()

	resp, err := http.Get(frontendProxy.URL)
	if err != nil {
		log.Fatal(err)
	}

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s", b)

}

func NewSingleHostReverseProxy(显示源文件)

func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy

NewSingleHostReverseProxy返回一个新的ReverseProxy,它将URL路由到目标中提供的方案,主机和基本路径。如果目标路径为“/base”,并且传入请求为“/dir”,则目标请求将为/base/dir。NewSingleHostReverseProxy不重写Host头。要重写Host头文件,请使用ReverseProxy直接使用自定义Director策略。

func (*ReverseProxy) ServeHTTP(显示源文件)

func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request)

type ServerConn(显示源文件)

ServerConn是Go早期HTTP实现的产物。它是Go的当前HTTP堆栈的低级,旧的和未使用的。我们应该在Go 1之前删除它。

Deprecated:改为在net/http包中使用Server。

type ServerConn struct {
        // contains filtered or unexported fields
}

func NewServerConn(显示源文件)

func NewServerConn(c net.Conn, r *bufio.Reader) *ServerConn

NewServerConn是Go早期HTTP实现的产物。它是Go的当前HTTP堆栈的低级,旧的和未使用的。我们应该在Go 1之前删除它。

Deprecated:改为在net/http包中使用Server。

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

func (sc *ServerConn) Close() error

Close调用劫持,然后关闭底层连接。

func (*ServerConn) Hijack(显示源文件)

func (sc *ServerConn) Hijack() (net.Conn, *bufio.Reader)

劫持分离ServerConn并返回底层连接以及可能有一些遗留数据的读取端bufio。在Read已经发出keep-alive逻辑的结束信号之前,可能会调用劫持。在读取或写入过程中,用户不应该调用劫持。

func (*ServerConn) Pending(显示源文件)

func (sc *ServerConn) Pending() int

挂起返回在连接上收到的未应答请求的数量。

func (*ServerConn) Read(显示源文件)

func (sc *ServerConn) Read() (*http.Request, error)

读取将返回线路上的下一个请求。如果优雅地确定没有更多请求(例如,在HTTP / 1.0连接上的第一个请求之后,或在HTTP/1.1连接上的Connection:close之后),则返回ErrPersistEOF。

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

func (sc *ServerConn) Write(req *http.Request, resp *http.Response) error

Write写入resp响应请求。要正常关闭连接,请将Response.Close字段设置为true。写操作应该被认为是可操作的,直到它返回一个错误,而不管在读方面返回的任何错误。

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 格式化字符串