目录 搜索
archive archive/tar archive/zip bufio bufio(缓存) builtin builtin(内置包) bytes bytes(包字节) compress compress/bzip2(压缩/bzip2) compress/flate(压缩/flate) compress/gzip(压缩/gzip) compress/lzw(压缩/lzw) compress/zlib(压缩/zlib) container container/heap(容器数据结构heap) container/list(容器数据结构list) container/ring(容器数据结构ring) context context(上下文) crypto crypto(加密) crypto/aes(加密/aes) crypto/cipher(加密/cipher) crypto/des(加密/des) crypto/dsa(加密/dsa) crypto/ecdsa(加密/ecdsa) crypto/elliptic(加密/elliptic) crypto/hmac(加密/hmac) crypto/md5(加密/md5) crypto/rand(加密/rand) crypto/rc4(加密/rc4) crypto/rsa(加密/rsa) crypto/sha1(加密/sha1) crypto/sha256(加密/sha256) crypto/sha512(加密/sha512) crypto/subtle(加密/subtle) crypto/tls(加密/tls) crypto/x509(加密/x509) crypto/x509/pkix(加密/x509/pkix) database database/sql(数据库/sql) database/sql/driver(数据库/sql/driver) debug debug/dwarf(调试/dwarf) debug/elf(调试/elf) debug/gosym(调试/gosym) debug/macho(调试/macho) debug/pe(调试/pe) debug/plan9obj(调试/plan9obj) encoding encoding(编码) encoding/ascii85(编码/ascii85) encoding/asn1(编码/asn1) encoding/base32(编码/base32) encoding/base64(编码/base64) encoding/binary(编码/binary) encoding/csv(编码/csv) encoding/gob(编码/gob) encoding/hex(编码/hex) encoding/json(编码/json) encoding/pem(编码/pem) encoding/xml(编码/xml) errors errors(错误) expvar expvar flag flag(命令行参数解析flag包) fmt fmt go go/ast(抽象语法树) go/build go/constant(常量) go/doc(文档) go/format(格式) go/importer go/parser go/printer go/scanner(扫描仪) go/token(令牌) go/types(类型) hash hash(散列) hash/adler32 hash/crc32 hash/crc64 hash/fnv html html html/template(模板) image image(图像) image/color(颜色) image/color/palette(调色板) image/draw(绘图) image/gif image/jpeg image/png index index/suffixarray io io io/ioutil log log log/syslog(日志系统) math math math/big math/big math/bits math/bits math/cmplx math/cmplx math/rand math/rand mime mime mime/multipart(多部分) mime/quotedprintable net net net/http net/http net/http/cgi net/http/cookiejar net/http/fcgi net/http/httptest net/http/httptrace net/http/httputil net/http/internal net/http/pprof net/mail net/mail net/rpc net/rpc net/rpc/jsonrpc net/smtp net/smtp net/textproto net/textproto net/url net/url os os os/exec os/signal os/user path path path/filepath(文件路径) plugin plugin(插件) reflect reflect(反射) regexp regexp(正则表达式) regexp/syntax runtime runtime(运行时) runtime/debug(调试) runtime/internal/sys runtime/pprof runtime/race(竞争) runtime/trace(执行追踪器) sort sort(排序算法) strconv strconv(转换) strings strings(字符串) sync sync(同步) sync/atomic(原子操作) syscall syscall(系统调用) testing testing(测试) testing/iotest testing/quick text text/scanner(扫描文本) text/tabwriter text/template(定义模板) text/template/parse time time(时间戳) unicode unicode unicode/utf16 unicode/utf8 unsafe unsafe
文字

  • 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 mainimport ("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 mainimport ("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 mainimport ("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 mainimport ("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。写操作应该被认为是可操作的,直到它返回一个错误,而不管在读方面返回的任何错误。

上一篇: 下一篇: