Package http

Overview ▾

包http提供HTTP客户端和服务器实现.

Get,Head,Post和PostForm发出HTTP(或HTTPS)请求:

resp, err := http.Get("http://example.com/")
...
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
...
resp, err := http.PostForm("http://example.com/form",
	url.Values{"key": {"Value"}, "id": {"123"}})

完成后,客户端必须关闭响应主体:

resp, err := http.Get("http://example.com/")
if err != nil {
	// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// ...

为了控制HTTP客户端标头,重定向策略和其他设置,请创建一个客户端:

client := &http.Client{
	CheckRedirect: redirectPolicyFunc,
}

resp, err := client.Get("http://example.com")
// ...

req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...

为了控制代理,TLS配置,保持活动,压缩和其他设置,请创建传输:

tr := &http.Transport{
	MaxIdleConns:       10,
	IdleConnTimeout:    30 * time.Second,
	DisableCompression: true,
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://example.com")

客户端和传输程序可以安全地被多个goroutine并发使用,并且效率仅应创建一次并重新使用.

ListenAndServe使用给定的地址和处理程序启动HTTP服务器. 该处理程序通常为nil,这意味着要使用DefaultServeMux. Handle和HandleFunc将处理程序添加到DefaultServeMux:

http.Handle("/foo", fooHandler)

http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})

log.Fatal(http.ListenAndServe(":8080", nil))

通过创建自定义服务器,可以更好地控制服务器的行为:

s := &http.Server{
	Addr:           ":8080",
	Handler:        myHandler,
	ReadTimeout:    10 * time.Second,
	WriteTimeout:   10 * time.Second,
	MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())

从Go 1.6开始,使用HTTPS时,http软件包对HTTP / 2协议具有透明支持. 必须禁用HTTP / 2的程序可以通过将Transport.TLSNextProto(对于客户端)或Server.TLSNextProto(对于服务器)设置为非空的空映射来执行此操作. 或者,当前支持以下GODEBUG环境变量:

GODEBUG=http2client=0  # disable HTTP/2 client support
GODEBUG=http2server=0  # disable HTTP/2 server support
GODEBUG=http2debug=1   # enable verbose HTTP/2 debug logs
GODEBUG=http2debug=2   # ... even more verbose, with frame dumps

Go的API兼容性保证不涵盖GODEBUG变量. 请先报告所有问题,然后再禁用HTTP / 2支持: https//golang.org/s/http2bug

http包的Transport和Server都自动为简单配置启用HTTP / 2支持. 要为更复杂的配置启用HTTP / 2,使用较低级别的HTTP / 2功能或使用Go的http2软件包的较新版本,请直接导入" golang.org/x/net/http2"并使用其ConfigureTransport和/或ConfigureServer功能. 通过golang.org/x/net/http2软件包手动配置HTTP / 2优先于net / http软件包的内置HTTP / 2支持.

Index ▾

Constants
Variables
func CanonicalHeaderKey(s string) string
func DetectContentType(data []byte) string
func Error(w ResponseWriter, error string, code int)
func Handle(pattern string, handler Handler)
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
func ListenAndServe(addr string, handler Handler) error
func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
func NotFound(w ResponseWriter, r *Request)
func ParseHTTPVersion(vers string) (major, minor int, ok bool)
func ParseTime(text string) (t time.Time, err error)
func ProxyFromEnvironment(req *Request) (*url.URL, error)
func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)
func Redirect(w ResponseWriter, r *Request, url string, code int)
func Serve(l net.Listener, handler Handler) error
func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)
func ServeFile(w ResponseWriter, r *Request, name string)
func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error
func SetCookie(w ResponseWriter, cookie *Cookie)
func StatusText(code int) string
type Client
    func (c *Client) CloseIdleConnections()
    func (c *Client) Do(req *Request) (*Response, error)
    func (c *Client) Get(url string) (resp *Response, err error)
    func (c *Client) Head(url string) (resp *Response, err error)
    func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)
    func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
type CloseNotifier
type ConnState
    func (c ConnState) String() string
type Cookie
    func (c *Cookie) String() string
type CookieJar
type Dir
    func (d Dir) Open(name string) (File, error)
type File
type FileSystem
type Flusher
type Handler
    func FileServer(root FileSystem) Handler
    func NotFoundHandler() Handler
    func RedirectHandler(url string, code int) Handler
    func StripPrefix(prefix string, h Handler) Handler
    func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler
type HandlerFunc
    func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)
type Header
    func (h Header) Add(key, value string)
    func (h Header) Clone() Header
    func (h Header) Del(key string)
    func (h Header) Get(key string) string
    func (h Header) Set(key, value string)
    func (h Header) Write(w io.Writer) error
    func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error
type Hijacker
type ProtocolError
    func (pe *ProtocolError) Error() string
type PushOptions
type Pusher
type Request
    func NewRequest(method, url string, body io.Reader) (*Request, error)
    func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
    func ReadRequest(b *bufio.Reader) (*Request, error)
    func (r *Request) AddCookie(c *Cookie)
    func (r *Request) BasicAuth() (username, password string, ok bool)
    func (r *Request) Clone(ctx context.Context) *Request
    func (r *Request) Context() context.Context
    func (r *Request) Cookie(name string) (*Cookie, error)
    func (r *Request) Cookies() []*Cookie
    func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
    func (r *Request) FormValue(key string) string
    func (r *Request) MultipartReader() (*multipart.Reader, error)
    func (r *Request) ParseForm() error
    func (r *Request) ParseMultipartForm(maxMemory int64) error
    func (r *Request) PostFormValue(key string) string
    func (r *Request) ProtoAtLeast(major, minor int) bool
    func (r *Request) Referer() string
    func (r *Request) SetBasicAuth(username, password string)
    func (r *Request) UserAgent() string
    func (r *Request) WithContext(ctx context.Context) *Request
    func (r *Request) Write(w io.Writer) error
    func (r *Request) WriteProxy(w io.Writer) error
type Response
    func Get(url string) (resp *Response, err error)
    func Head(url string) (resp *Response, err error)
    func Post(url, contentType string, body io.Reader) (resp *Response, err error)
    func PostForm(url string, data url.Values) (resp *Response, err error)
    func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)
    func (r *Response) Cookies() []*Cookie
    func (r *Response) Location() (*url.URL, error)
    func (r *Response) ProtoAtLeast(major, minor int) bool
    func (r *Response) Write(w io.Writer) error
type ResponseWriter
type RoundTripper
    func NewFileTransport(fs FileSystem) RoundTripper
type SameSite
type ServeMux
    func NewServeMux() *ServeMux
    func (mux *ServeMux) Handle(pattern string, handler Handler)
    func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
    func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)
    func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
type Server
    func (srv *Server) Close() error
    func (srv *Server) ListenAndServe() error
    func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error
    func (srv *Server) RegisterOnShutdown(f func())
    func (srv *Server) Serve(l net.Listener) error
    func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error
    func (srv *Server) SetKeepAlivesEnabled(v bool)
    func (srv *Server) Shutdown(ctx context.Context) error
type Transport
    func (t *Transport) CancelRequest(req *Request)
    func (t *Transport) Clone() *Transport
    func (t *Transport) CloseIdleConnections()
    func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)
    func (t *Transport) RoundTrip(req *Request) (*Response, error)

Package files

client.go clone.go cookie.go doc.go filetransport.go fs.go h2_bundle.go header.go http.go jar.go method.go request.go response.go roundtrip.go server.go sniff.go socks_bundle.go status.go transfer.go transport.go

Constants

常见的HTTP方法.

除非另有说明,否则它们在RFC 7231第4.3节中定义.

const (
    MethodGet     = "GET"
    MethodHead    = "HEAD"
    MethodPost    = "POST"
    MethodPut     = "PUT"
    MethodPatch   = "PATCH" // RFC 5789
    MethodDelete  = "DELETE"
    MethodConnect = "CONNECT"
    MethodOptions = "OPTIONS"
    MethodTrace   = "TRACE"
)

向IANA注册的HTTP状态代码. 请参阅: https//www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

const (
    StatusContinue           = 100 // RFC 7231, 6.2.1
    StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
    StatusProcessing         = 102 // RFC 2518, 10.1
    StatusEarlyHints         = 103 // RFC 8297

    StatusOK                   = 200 // RFC 7231, 6.3.1
    StatusCreated              = 201 // RFC 7231, 6.3.2
    StatusAccepted             = 202 // RFC 7231, 6.3.3
    StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
    StatusNoContent            = 204 // RFC 7231, 6.3.5
    StatusResetContent         = 205 // RFC 7231, 6.3.6
    StatusPartialContent       = 206 // RFC 7233, 4.1
    StatusMultiStatus          = 207 // RFC 4918, 11.1
    StatusAlreadyReported      = 208 // RFC 5842, 7.1
    StatusIMUsed               = 226 // RFC 3229, 10.4.1

    StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
    StatusMovedPermanently = 301 // RFC 7231, 6.4.2
    StatusFound            = 302 // RFC 7231, 6.4.3
    StatusSeeOther         = 303 // RFC 7231, 6.4.4
    StatusNotModified      = 304 // RFC 7232, 4.1
    StatusUseProxy         = 305 // RFC 7231, 6.4.5

    StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
    StatusPermanentRedirect = 308 // RFC 7538, 3

    StatusBadRequest                   = 400 // RFC 7231, 6.5.1
    StatusUnauthorized                 = 401 // RFC 7235, 3.1
    StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
    StatusForbidden                    = 403 // RFC 7231, 6.5.3
    StatusNotFound                     = 404 // RFC 7231, 6.5.4
    StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
    StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
    StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
    StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
    StatusConflict                     = 409 // RFC 7231, 6.5.8
    StatusGone                         = 410 // RFC 7231, 6.5.9
    StatusLengthRequired               = 411 // RFC 7231, 6.5.10
    StatusPreconditionFailed           = 412 // RFC 7232, 4.2
    StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
    StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
    StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
    StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
    StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
    StatusTeapot                       = 418 // RFC 7168, 2.3.3
    StatusMisdirectedRequest           = 421 // RFC 7540, 9.1.2
    StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
    StatusLocked                       = 423 // RFC 4918, 11.3
    StatusFailedDependency             = 424 // RFC 4918, 11.4
    StatusTooEarly                     = 425 // RFC 8470, 5.2.
    StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
    StatusPreconditionRequired         = 428 // RFC 6585, 3
    StatusTooManyRequests              = 429 // RFC 6585, 4
    StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
    StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

    StatusInternalServerError           = 500 // RFC 7231, 6.6.1
    StatusNotImplemented                = 501 // RFC 7231, 6.6.2
    StatusBadGateway                    = 502 // RFC 7231, 6.6.3
    StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
    StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
    StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
    StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
    StatusInsufficientStorage           = 507 // RFC 4918, 11.5
    StatusLoopDetected                  = 508 // RFC 5842, 7.2
    StatusNotExtended                   = 510 // RFC 2774, 7
    StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

DefaultMaxHeaderBytes是HTTP请求中标头的最大允许大小. 可以通过设置Server.MaxHeaderBytes来覆盖它.

const DefaultMaxHeaderBytes = 1 << 20 // 1 MB

DefaultMaxIdleConnsPerHost是Transport的MaxIdleConnsPerHost的默认值.

const DefaultMaxIdleConnsPerHost = 2

TimeFormat是在HTTP标头中生成时间时要使用的时间格式. 就像time.RFC1123一样,但是将GMT硬编码为时区. 格式化的时间必须采用UTC格式才能生成正确的格式.

有关解析此时间格式的信息,请参见ParseTime.

const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"

TrailerPrefix是ResponseWriter的魔术前缀.Header映射键(如果存在的话)表示映射条目实际上是响应尾部的,而不是响应头的. ServeHTTP调用完成后,前缀将被删除,并且值将在预告片中发送.

此机制仅适用于在写入标头之前未知的预告片. 如果在写头之前固定的或已知的预告片组,则首选普通的Go预告片机制:

https://golang.org/pkg/net/http/#ResponseWriter
https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
const TrailerPrefix = "Trailer:"

Variables

var (
    // ErrNotSupported is returned by the Push method of Pusher
    // implementations to indicate that HTTP/2 Push support is not
    // available.
    ErrNotSupported = &ProtocolError{"feature not supported"}

    // Deprecated: ErrUnexpectedTrailer is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"}

    // ErrMissingBoundary is returned by Request.MultipartReader when the
    // request's Content-Type does not include a "boundary" parameter.
    ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"}

    // ErrNotMultipart is returned by Request.MultipartReader when the
    // request's Content-Type is not multipart/form-data.
    ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"}

    // Deprecated: ErrHeaderTooLong is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrHeaderTooLong = &ProtocolError{"header too long"}

    // Deprecated: ErrShortBody is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrShortBody = &ProtocolError{"entity body too short"}

    // Deprecated: ErrMissingContentLength is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"}
)

HTTP服务器使用的错误.

var (
    // ErrBodyNotAllowed is returned by ResponseWriter.Write calls
    // when the HTTP method or response code does not permit a
    // body.
    ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")

    // ErrHijacked is returned by ResponseWriter.Write calls when
    // the underlying connection has been hijacked using the
    // Hijacker interface. A zero-byte write on a hijacked
    // connection will return ErrHijacked without any other side
    // effects.
    ErrHijacked = errors.New("http: connection has been hijacked")

    // ErrContentLength is returned by ResponseWriter.Write calls
    // when a Handler set a Content-Length response header with a
    // declared size and then attempted to write more bytes than
    // declared.
    ErrContentLength = errors.New("http: wrote more than the declared Content-Length")

    // Deprecated: ErrWriteAfterFlush is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrWriteAfterFlush = errors.New("unused")
)
var (
    // ServerContextKey is a context key. It can be used in HTTP
    // handlers with Context.Value to access the server that
    // started the handler. The associated value will be of
    // type *Server.
    ServerContextKey = &contextKey{"http-server"}

    // LocalAddrContextKey is a context key. It can be used in
    // HTTP handlers with Context.Value to access the local
    // address the connection arrived on.
    // The associated value will be of type net.Addr.
    LocalAddrContextKey = &contextKey{"local-addr"}
)

DefaultClient是默认客户端,由Get,Head和Post使用.

var DefaultClient = &Client{}

DefaultServeMux是Serve使用的默认ServeMux.

var DefaultServeMux = &defaultServeMux

ErrAbortHandler是一个中止恐慌值,用于中止处理程序. 尽管来自ServeHTTP的任何恐慌都会中止对客户端的响应,但是使用ErrAbortHandler进行恐慌也会抑制将堆栈跟踪记录到服务器的错误日志中.

var ErrAbortHandler = errors.New("net/http: abort Handler")

在关闭请求或响应主体后,读取请求或响应主体时,将返回ErrBodyReadAfterClose. 这通常在HTTP处理程序在其ResponseWriter上调用WriteHeader或Write后读取正文时发生.

var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")

在已超时的处理程序中,在ResponseWriter Write调用上返回ErrHandlerTimeout.

var ErrHandlerTimeout = errors.New("http: Handler timeout")

读取格式不正确的分块编码的请求或响应正文时,将返回ErrLineTooLong.

var ErrLineTooLong = internal.ErrLineTooLong

当提供的文件字段名称不存在于请求中或文件字段中时,FormFile返回ErrMissingFile.

var ErrMissingFile = errors.New("http: no such file")

未找到Cookie时,Request的Cookie方法将返回ErrNoCookie.

var ErrNoCookie = errors.New("http: named cookie not present")

如果不存在Location标头,则由Response的Location方法返回ErrNoLocation.

var ErrNoLocation = errors.New("http: no Location header in response")

调用Shutdown或Close之后,服务器的Serve,ServeTLS,ListenAndServe和ListenAndServeTLS方法返回ErrServerClosed.

var ErrServerClosed = errors.New("http: Server closed")

ErrSkipAltProtocol是由Transport.RegisterProtocol定义的标记错误值.

var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")

Client.CheckRedirect挂钩可以返回ErrUseLastResponse,以控制如何处理重定向. 如果返回,则不发送下一个请求,并且返回最近的响应且其主体未关闭.

var ErrUseLastResponse = errors.New("net/http: use last response")

NoBody is an io.ReadCloser with no bytes. Read always returns EOF and Close always returns nil. It can be used in an outgoing client request to explicitly signal that a request has zero bytes. An alternative, however, is to simply set Request.Body to nil.

var NoBody = noBody{}

func CanonicalHeaderKey

func CanonicalHeaderKey(s string) string

CanonicalHeaderKey返回标头键s的规范格式. 规范化将第一个字母和连字符后的任何字母转换为大写; 其余的将转换为小写. 例如,"接受编码"的规范密钥为"接受编码". 如果s包含空格或无效的头字段字节,则返回它而无需修改.

func DetectContentType

func DetectContentType(data []byte) string

DetectContentType实现https://mimesniff.spec.whatwg.org/上描述的算法,以确定给定数据的Content-Type. 它最多考虑前512个字节的数据. DetectContentType始终返回有效的MIME类型:如果无法确定更具体的类型,则返回" application / octet-stream".

func Error

func Error(w ResponseWriter, error string, code int)

错误使用指定的错误消息和HTTP代码回复请求. 否则,它不会结束请求; 调用者应确保不再对w进行写操作. 错误消息应为纯文本.

func Handle

func Handle(pattern string, handler Handler)

Handle在DefaultServeMux中为给定模式注册处理程序. ServeMux的文档说明了如何匹配模式.

Example

func HandleFunc

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc在DefaultServeMux中注册给定模式的处理函数. ServeMux的文档说明了如何匹配模式.

Example

func ListenAndServe

func ListenAndServe(addr string, handler Handler) error

ListenAndServe侦听TCP网络地址addr,然后调用Serve with handler处理传入连接上的请求. 接受的连接配置为启用TCP保持活动状态.

该处理程序通常为nil,在这种情况下,将使用DefaultServeMux.

ListenAndServe always returns a non-nil error.

Example

func ListenAndServeTLS

func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error

ListenAndServeTLS的行为与ListenAndServe相同,不同之处在于它需要HTTPS连接. 另外,必须提供包含证书和服务器的匹配私钥的文件. 如果证书是由证书颁发机构签名的,则certFile应该是服务器证书,任何中间件和CA证书的串联.

Example

func MaxBytesReader

func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser

MaxBytesReader与io.LimitReader相似,但旨在限制传入请求主体的大小. 与io.LimitReader相比,MaxBytesReader的结果是ReadCloser,对于超出限制的Read返回非EOF错误,并在调用其Close方法时关闭基础阅读器.

MaxBytesReader可以防止客户端意外或恶意发送大请求并浪费服务器资源.

func NotFound

func NotFound(w ResponseWriter, r *Request)

NotFound回复请求,并显示HTTP 404 not found错误.

func ParseHTTPVersion

func ParseHTTPVersion(vers string) (major, minor int, ok bool)

ParseHTTPVersion解析HTTP版本字符串. " HTTP / 1.0"返回(1、0,true).

func ParseTime 1.1

func ParseTime(text string) (t time.Time, err error)

ParseTime解析时间标头(例如Date:标头),尝试使用HTTP / 1.1允许的三种格式:TimeFormat,time.RFC850和time.ANSIC.

func ProxyFromEnvironment

func ProxyFromEnvironment(req *Request) (*url.URL, error)

ProxyFromEnvironment返回用于给定请求的代理的URL,如环境变量HTTP_PROXY,HTTPS_PROXY和NO_PROXY(或其小写版本)所指示. 对于HTTPS请求,HTTPS_PROXY优先于HTTP_PROXY.

环境值可以是完整的URL或" host [:port]",在这种情况下,假定使用" http"方案. 如果值的格式不同,则返回错误.

A nil URL and nil error are returned if no proxy is defined in the environment, or a proxy should not be used for the given request, as defined by NO_PROXY.

在特殊情况下,如果req.URL.Host为" localhost"(有或没有端口号),则将返回nil URL和nil错误.

func ProxyURL

func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)

ProxyURL返回始终返回相同URL的代理功能(用于传输).

func Redirect

func Redirect(w ResponseWriter, r *Request, url string, code int)

重定向通过重定向到url来答复请求,URL可能是相对于请求路径的路径.

提供的代码应在3xx范围内,通常为StatusMovedPermanently,StatusFound或StatusSeeOther.

如果尚未设置Content-Type标头,则重定向会将其设置为" text / html; charset = utf-8"并编写一个小的HTML正文. 将Content-Type标头设置为任何值(包括nil)将禁用该行为.

func Serve

func Serve(l net.Listener, handler Handler) error

服务在侦听器l上接受传入的HTTP连接,从而为每个侦听器创建一个新的服务goroutine. 服务goroutine读取请求,然后调用处理程序以回复请求.

该处理程序通常为nil,在这种情况下,将使用DefaultServeMux.

仅当侦听器返回* tls.Conn连接并且在TLS Config.NextProtos中将它们配置为" h2"时,才启用HTTP / 2支持.

服务始终返回非零错误.

func ServeContent

func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)

ServeContent replies to the request using the content in the provided ReadSeeker. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests.

如果未设置响应的Content-Type标头,则ServeContent首先尝试从名称的文件扩展名中推断出类型,如果失败,则退回到读取内容的第一块并将其传递给DetectContentType. 该名称否则未使用; 特别是它可以为空,并且永远不会在响应中发送.

如果modtime不是零时间或Unix时代,则ServeContent会将其包含在响应的Last-Modified头中. 如果请求中包含If-Modified-Since标头,则ServeContent使用modtime来决定是否完全需要发送内容.

内容的Seek方法必须起作用:ServeContent使用对内容结尾的查找来确定其大小.

如果调用方设置了按照RFC 7232第2.3节格式化的w的ETag标头,则ServeContent使用它来处理使用If-Match,If-None-Match或If-Range的请求.

请注意,* os.File实现了io.ReadSeeker接口.

func ServeFile

func ServeFile(w ResponseWriter, r *Request, name string)

ServeFile使用命名文件或目录的内容答复请求.

如果提供的文件或目录名称是相对路径,则会相对于当前目录进行解释,并且可能会升至父目录. 如果提供的名称是根据用户输入构造的,则应在调用ServeFile之前对其进行清理.

作为预防措施,ServeFile将拒绝r.URL.Path包含" .."路径元素的请求; 这样可以防止调用者可能不安全地使用r.URL.Path上的filepath.Join而不对其进行清理,然后使用该filepath.Join结果作为name参数.

作为另一种特殊情况,ServeFile将r.URL.Path以" /index.html"结尾的任何请求重定向到同一路径,而没有最终的" index.html". 为避免此类重定向,请修改路径或使用ServeContent.

除了这两种特殊情况外,ServeFile不使用r.URL.Path来选择要提供的文件或目录. 仅使用name参数中提供的文件或目录.

func ServeTLS 1.9

func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error

ServeTLS在侦听器l上接受传入的HTTPS连接,从而为每个侦听器创建一个新的服务goroutine. 服务goroutine读取请求,然后调用处理程序以回复请求.

该处理程序通常为nil,在这种情况下,将使用DefaultServeMux.

另外,必须提供包含证书和服务器的匹配私钥的文件. 如果证书是由证书颁发机构签名的,则certFile应该是服务器证书,任何中间件和CA证书的串联.

ServeTLS始终返回非nil错误.

func SetCookie

func SetCookie(w ResponseWriter, cookie *Cookie)

SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func StatusText

func StatusText(code int) string

StatusText返回HTTP状态代码的文本. 如果代码未知,它将返回空字符串.

type Client

客户端是HTTP客户端. 它的零值(DefaultClient)是使用DefaultTransport的可用客户端.

客户端的传输通常具有内部状态(缓存的TCP连接),因此应重新使用客户端,而不是根据需要创建客户端. 客户端可以安全地被多个goroutine并发使用.

客户端比RoundTripper(例如Transport)更高级别,并且还处理HTTP详细信息,例如cookie和重定向.

When following redirects, the Client will forward all headers set on the initial Request except:

•将敏感的标头(如"授权"," WWW-身份验证"和" Cookie")转发到不受信任的目标时. 当重定向到与子域不匹配或与初始域不完全匹配的域时,将忽略这些标头. 例如,从" foo.com"重定向到" foo.com"或" sub.foo.com"将转发敏感标头,但重定向到" bar.com"则不会.

•用非零值的Cookie Jar转发" Cookie"标头时. 由于每个重定向可能会更改Cookie罐的状态,因此重定向可能会更改初始请求中设置的Cookie. 当转发" Cookie"标头时,任何突变的cookie都将被省略,并期望Jar将插入具有更新值的那些突变的cookie(假设原点匹配). 如果Jar为零,则将转发原始cookie,而不进行任何更改.

type Client struct {
    // Transport specifies the mechanism by which individual
    // HTTP requests are made.
    // If nil, DefaultTransport is used.
    Transport RoundTripper

    // CheckRedirect specifies the policy for handling redirects.
    // If CheckRedirect is not nil, the client calls it before
    // following an HTTP redirect. The arguments req and via are
    // the upcoming request and the requests made already, oldest
    // first. If CheckRedirect returns an error, the Client's Get
    // method returns both the previous Response (with its Body
    // closed) and CheckRedirect's error (wrapped in a url.Error)
    // instead of issuing the Request req.
    // As a special case, if CheckRedirect returns ErrUseLastResponse,
    // then the most recent response is returned with its body
    // unclosed, along with a nil error.
    //
    // If CheckRedirect is nil, the Client uses its default policy,
    // which is to stop after 10 consecutive requests.
    CheckRedirect func(req *Request, via []*Request) error

    // Jar specifies the cookie jar.
    //
    // The Jar is used to insert relevant cookies into every
    // outbound Request and is updated with the cookie values
    // of every inbound Response. The Jar is consulted for every
    // redirect that the Client follows.
    //
    // If Jar is nil, cookies are only sent if they are explicitly
    // set on the Request.
    Jar CookieJar

    // Timeout specifies a time limit for requests made by this
    // Client. The timeout includes connection time, any
    // redirects, and reading the response body. The timer remains
    // running after Get, Head, Post, or Do return and will
    // interrupt reading of the Response.Body.
    //
    // A Timeout of zero means no timeout.
    //
    // The Client cancels requests to the underlying Transport
    // as if the Request's Context ended.
    //
    // For compatibility, the Client will also use the deprecated
    // CancelRequest method on Transport if found. New
    // RoundTripper implementations should use the Request's Context
    // for cancellation instead of implementing CancelRequest.
    Timeout time.Duration // Go 1.3
}

func (*Client) CloseIdleConnections 1.12

func (c *Client) CloseIdleConnections()

CloseIdleConnections关闭其传输上先前与先前请求连接的任何连接,但现在处于"保持活动"状态而处于空闲状态. 它不会中断当前正在使用的任何连接.

如果客户端的传输没有CloseIdleConnections方法,则此方法不执行任何操作.

func (*Client) Do

func (c *Client) Do(req *Request) (*Response, error)

请按照客户端上配置的策略(例如重定向,Cookie,身份验证)发送HTTP请求并返回HTTP响应.

如果是由客户端策略(例如CheckRedirect)或无法讲HTTP(例如网络连接问题)引起的,则返回错误. 非2xx状态代码不会导致错误.

如果返回的错误为nil,则响应将包含一个非零的Body,希望用户将其关闭. 如果未同时将主体读入EOF并关闭,则客户端的基础RoundTripper(通常是Transport)可能无法将与服务器的持久TCP连接重新用于后续的"保持活动"请求.

请求主体(如果非零)将被基础传输关闭,即使发生错误也是如此.

出错时,任何响应都可以忽略. 仅当CheckRedirect失败并且返回的Response.Body已关闭时,才会出现具有非nil错误的非nil响应.

通常,将使用Get,Post或PostForm代替Do.

如果服务器回复重定向,则客户端首先使用CheckRedirect函数来确定是否应遵循重定向. 如果允许,则301、302或303重定向会导致后续请求使用HTTP方法GET(如果原始请求为HEAD,则为HEAD),而没有正文. 如果定义了Request.GetBody函数,则307或308重定向将保留原始的HTTP方法和主体. NewRequest函数自动为常见的标准库主体类型设置GetBody.

返回的任何错误均为* url.Error类型. 如果请求超时或被取消,则url.Error值的Timeout方法将报告true.

func (*Client) Get

func (c *Client) Get(url string) (resp *Response, err error)

获取将GET发送到指定的URL. 如果响应是以下重定向代码之一,则Get在调用客户端的CheckRedirect函数后遵循重定向:

301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)

如果客户端的CheckRedirect函数失败或存在HTTP协议错误,则返回错误. 非2xx响应不会导致错误. 返回的任何错误均为* url.Error类型. 如果请求超时或被取消,则url.Error值的Timeout方法将报告true.

当err为nil时,resp始终包含非nil resp.Body. 呼叫者完成阅读后,应关闭resp.Body.

要使用自定义标头发出请求,请使用NewRequest和Client.Do.

func (*Client) Head

func (c *Client) Head(url string) (resp *Response, err error)

Head向指定的URL发出HEAD. 如果响应是以下重定向代码之一,则Head在调用客户端的CheckRedirect函数后遵循重定向:

301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)

func (*Client) Post

func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)

Post发布POST到指定的URL.

呼叫者完成阅读后,应关闭resp.Body.

如果提供的主体是io.Closer,则在请求后将其关闭.

若要设置自定义标头,请使用NewRequest和Client.Do.

有关如何处理重定向的详细信息,请参阅Client.Do方法文档.

func (*Client) PostForm

func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)

PostForm向指定的URL发出POST,并将数据的键和值URL编码为请求正文.

Content-Type标头设置为application / x-www-form-urlencoded. 若要设置其他标头,请使用NewRequest和Client.Do.

当err为nil时,resp始终包含非nil resp.Body. 呼叫者完成阅读后,应关闭resp.Body.

有关如何处理重定向的详细信息,请参阅Client.Do方法文档.

type CloseNotifier 1.1

CloseNotifier接口由ResponseWriters实现,它可以检测基础连接何时消失.

如果客户端在响应准备就绪之前已断开连接,则可以使用此机制取消服务器上的长时间操作.

不推荐使用:CloseNotifier接口早于Go的上下文包. 新代码应改为使用Request.Context.

type CloseNotifier interface {
    // CloseNotify returns a channel that receives at most a
    // single value (true) when the client connection has gone
    // away.
    //
    // CloseNotify may wait to notify until Request.Body has been
    // fully read.
    //
    // After the Handler has returned, there is no guarantee
    // that the channel receives a value.
    //
    // If the protocol is HTTP/1.1 and CloseNotify is called while
    // processing an idempotent request (such a GET) while
    // HTTP/1.1 pipelining is in use, the arrival of a subsequent
    // pipelined request may cause a value to be sent on the
    // returned channel. In practice HTTP/1.1 pipelining is not
    // enabled in browsers and not seen often in the wild. If this
    // is a problem, use HTTP/2 or only use CloseNotify on methods
    // such as POST.
    CloseNotify() <-chan bool
}

type ConnState 1.3

ConnState表示客户端与服务器的连接状态. 由可选的Server.ConnState挂钩使用.

type ConnState int
const (
    // StateNew represents a new connection that is expected to
    // send a request immediately. Connections begin at this
    // state and then transition to either StateActive or
    // StateClosed.
    StateNew ConnState = iota

    // StateActive represents a connection that has read 1 or more
    // bytes of a request. The Server.ConnState hook for
    // StateActive fires before the request has entered a handler
    // and doesn't fire again until the request has been
    // handled. After the request is handled, the state
    // transitions to StateClosed, StateHijacked, or StateIdle.
    // For HTTP/2, StateActive fires on the transition from zero
    // to one active request, and only transitions away once all
    // active requests are complete. That means that ConnState
    // cannot be used to do per-request work; ConnState only notes
    // the overall state of the connection.
    StateActive

    // StateIdle represents a connection that has finished
    // handling a request and is in the keep-alive state, waiting
    // for a new request. Connections transition from StateIdle
    // to either StateActive or StateClosed.
    StateIdle

    // StateHijacked represents a hijacked connection.
    // This is a terminal state. It does not transition to StateClosed.
    StateHijacked

    // StateClosed represents a closed connection.
    // This is a terminal state. Hijacked connections do not
    // transition to StateClosed.
    StateClosed
)

func (ConnState) String 1.3

func (c ConnState) String() string

Cookie代表在HTTP响应的Set-Cookie标头或HTTP请求的Cookie标头中发送的HTTP Cookie.

有关详细信息,请参见https://tools.ietf.org/html/rfc6265 .

type Cookie struct {
    Name  string
    Value string

    Path       string    // optional
    Domain     string    // optional
    Expires    time.Time // optional
    RawExpires string    // for reading cookies only

    // MaxAge=0 means no 'Max-Age' attribute specified.
    // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
    // MaxAge>0 means Max-Age attribute present and given in seconds
    MaxAge   int
    Secure   bool
    HttpOnly bool
    SameSite SameSite // Go 1.11
    Raw      string
    Unparsed []string // Raw text of unparsed attribute-value pairs
}

func (*Cookie) String

func (c *Cookie) String() string

String返回Cookie的序列化,以用于Cookie标头(如果仅设置了Name和Value)或Set-Cookie响应标头(如果设置了其他字段)中. 如果c为nil或c.Name无效,则返回空字符串.

type CookieJar

CookieJar管理HTTP请求中cookie的存储和使用.

CookieJar的实现必须安全,可以被多个goroutine并发使用.

net / http / cookiejar软件包提供了CookieJar实现.

type CookieJar interface {
    // SetCookies handles the receipt of the cookies in a reply for the
    // given URL.  It may or may not choose to save the cookies, depending
    // on the jar's policy and implementation.
    SetCookies(u *url.URL, cookies []*Cookie)

    // Cookies returns the cookies to send in a request for the given URL.
    // It is up to the implementation to honor the standard cookie use
    // restrictions such as in RFC 6265.
    Cookies(u *url.URL) []*Cookie
}

type Dir

Dir使用限于特定目录树的本机文件系统来实现FileSystem.

虽然FileSystem.Open方法采用'/'分隔的路径,但Dir的字符串值是本机文件系统上的文件名,而不是URL,因此它由filepath.Separator分隔,不一定是'/'.

请注意,Dir允许访问以句点开头的文件和目录,该文件和目录可能会公开敏感目录(如.git目录)或敏感文件(如.htpasswd). 要排除前导文件,请从服务器中删除文件/目录或创建自定义FileSystem实现.

空目录将被视为".".

type Dir string

func (Dir) Open

func (d Dir) Open(name string) (File, error)

Open使用os.Open实现FileSystem,打开文件以读取root以及相对于目录d的文件.

type File

File由FileSystem的Open方法返回,并且可以由FileServer实现提供服务.

这些方法的行为应与* os.File上的行为相同.

type File interface {
    io.Closer
    io.Reader
    io.Seeker
    Readdir(count int) ([]os.FileInfo, error)
    Stat() (os.FileInfo, error)
}

type FileSystem

FileSystem实现对命名文件集合的访问. 无论主机操作系统的约定如何,文件路径中的元素都用斜杠('/',U + 002F)字符分隔.

type FileSystem interface {
    Open(name string) (File, error)
}

type Flusher

The Flusher interface is implemented by ResponseWriters that allow an HTTP handler to flush buffered data to the client.

默认的HTTP / 1.x和HTTP / 2 ResponseWriter实现支持Flusher,但ResponseWriter包装器可能不支持. 处理程序应始终在运行时测试此功能.

请注意,即使对于支持Flush的ResponseWriters,如果客户端通过HTTP代理连接,在响应完成之前,缓冲的数据也可能无法到达客户端.

type Flusher interface {
    // Flush sends any buffered data to the client.
    Flush()
}

type Handler

处理程序响应HTTP请求.

ServeHTTP应该将回复标头和数据写入ResponseWriter,然后返回. 返回信号表明请求已完成; 在ServeHTTP调用完成后或与之同时使用ResponseWriter或从Request.Body中读取是无效的.

根据HTTP客户端软件,HTTP协议版本以及客户端和Go服务器之间的任何中介,可能无法在写入ResponseWriter之后从Request.Body中读取. 谨慎的处理程序应先阅读Request.Body,然后再进行回复.

除读取正文外,处理程序不应修改提供的请求.

如果出现ServeHTTP紧急情况,则服务器(ServeHTTP的调用方)将假定紧急情况的影响与活动请求无关. 它恢复紧急状态,将堆栈跟踪记录到服务器错误日志中,然后关闭网络连接或发送HTTP / 2 RST_STREAM,具体取决于HTTP协议. 要中止处理程序,以便客户端看到中断的响应,但服务器不会记录错误,请惊慌于ErrAbortHandler值.

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

func FileServer

func FileServer(root FileSystem) Handler

FileServer返回一个处理程序,该处理程序以根目录为根的文件系统内容为HTTP请求提供服务.

要使用操作系统的文件系统实现,请使用http.Dir:

http.Handle("/", http.FileServer(http.Dir("/tmp")))

作为一种特殊情况,返回的文件服务器会将以" /index.html"结尾的所有请求重定向到同一路径,而没有最终的" index.html".

Example

范例(DotFileHiding)

示例(StripPrefix)

func NotFoundHandler

func NotFoundHandler() Handler

NotFoundHandler返回一个简单的请求处理程序,该处理程序使用" 404页面未找到"答复来答复每个请求.

Example

func RedirectHandler

func RedirectHandler(url string, code int) Handler

RedirectHandler返回一个请求处理程序,该处理程序使用给定的状态码将收到的每个请求重定向到给定的url.

提供的代码应在3xx范围内,通常为StatusMovedPermanently,StatusFound或StatusSeeOther.

func StripPrefix

func StripPrefix(prefix string, h Handler) Handler

StripPrefix通过从请求URL的路径中删除给定前缀并调用处理程序h,返回处理HTTP请求的处理程序. StripPrefix通过回答HTTP 404 not found错误来处理对不以前缀开头的路径的请求.

Example

func TimeoutHandler

func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler

TimeoutHandler返回一个在给定时间限制下运行h的Handler.

新的处理程序调用h.ServeHTTP来处理每个请求,但是如果调用的运行时间超过其时间限制,则该处理程序将以503 Service Unavailable错误和主体中的给定消息作为响应. (如果msg为空,将发送适当的默认消息.)在这样的超时之后,用h对其ResponseWriter进行写操作将返回ErrHandlerTimeout.

TimeoutHandler支持Flusher和Pusher接口,但不支持Hijacker接口.

type HandlerFunc

HandlerFunc类型是一个适配器,允许将普通功能用作HTTP处理程序. 如果f是具有适当签名的函数,则HandlerFunc(f)是调用f的处理程序.

type HandlerFunc func(ResponseWriter, *Request)

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)

ServeHTTP调用f(w,r).

标头代表HTTP标头中的键/值对.

密钥应采用CanonicalHeaderKey返回的规范形式.

type Header map[string][]string

func (Header) Add

func (h Header) Add(key, value string)

Add将键,值对添加到标题. 它附加到与键关联的任何现有值. 密钥不区分大小写; 它由CanonicalHeaderKey规范化.

func (Header) Clone 1.13

func (h Header) Clone() Header

如果h为nil,则Clone返回h或nil的副本.

func (Header) Del

func (h Header) Del(key string)

Del删除与键关联的值. 密钥不区分大小写; 它由CanonicalHeaderKey规范化.

func (Header) Get

func (h Header) Get(key string) string

Get获取与给定键关联的第一个值. 如果没有与键关联的值,则Get返回"". 不区分大小写; textproto.CanonicalMIMEHeaderKey用于规范化所提供的密钥. 要访问键的多个值或使用非规范键,请直接访问地图.

func (Header) Set

func (h Header) Set(key, value string)

Set将与key关联的标题条目设置为单个元素值. 它替换了与键关联的任何现有值. 密钥不区分大小写; 它由textproto.CanonicalMIMEHeaderKey规范化. 要使用非规范键,请直接分配给地图.

func (Header) Write

func (h Header) Write(w io.Writer) error

写以有线格式写标题.

func (Header) WriteSubset

func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error

WriteSubset以有线格式写入标头. 如果exclude不为nil,则不会写入exclude [key] == true的键.

type Hijacker

Hijacker接口是由ResponseWriters实现的,它允许HTTP处理程序接管连接.

HTTP / 1.x连接的默认ResponseWriter支持Hijacker,但HTTP / 2连接有意不支持. ResponseWriter包装器也可能不支持Hijacker. 处理程序应始终在运行时测试此功能.

type Hijacker interface {
    // Hijack lets the caller take over the connection.
    // After a call to Hijack the HTTP server library
    // will not do anything else with the connection.
    //
    // It becomes the caller's responsibility to manage
    // and close the connection.
    //
    // The returned net.Conn may have read or write deadlines
    // already set, depending on the configuration of the
    // Server. It is the caller's responsibility to set
    // or clear those deadlines as needed.
    //
    // The returned bufio.Reader may contain unprocessed buffered
    // data from the client.
    //
    // After a call to Hijack, the original Request.Body must not
    // be used. The original Request's Context remains valid and
    // is not canceled until the Request's ServeHTTP method
    // returns.
    Hijack() (net.Conn, *bufio.ReadWriter, error)
}

Example

type ProtocolError

ProtocolError表示HTTP协议错误.

弃用:并非http包中与协议错误相关的所有错误均属于ProtocolError类型.

type ProtocolError struct {
    ErrorString string
}

func (*ProtocolError) Error

func (pe *ProtocolError) Error() string

type PushOptions 1.8

PushOptions描述了Pusher.Push的选项.

type PushOptions struct {
    // Method specifies the HTTP method for the promised request.
    // If set, it must be "GET" or "HEAD". Empty means "GET".
    Method string

    // Header specifies additional promised request headers. This cannot
    // include HTTP/2 pseudo header fields like ":path" and ":scheme",
    // which will be added automatically.
    Header Header
}

type Pusher 1.8

Pusher是由ResponseWriters实现的支持HTTP / 2服务器推送的接口. 有关更多背景信息,请参见https://tools.ietf.org/html/rfc7540#section-8.2 .

type Pusher interface {
    // Push initiates an HTTP/2 server push. This constructs a synthetic
    // request using the given target and options, serializes that request
    // into a PUSH_PROMISE frame, then dispatches that request using the
    // server's request handler. If opts is nil, default options are used.
    //
    // The target must either be an absolute path (like "/path") or an absolute
    // URL that contains a valid host and the same scheme as the parent request.
    // If the target is a path, it will inherit the scheme and host of the
    // parent request.
    //
    // The HTTP/2 spec disallows recursive pushes and cross-authority pushes.
    // Push may or may not detect these invalid pushes; however, invalid
    // pushes will be detected and canceled by conforming clients.
    //
    // Handlers that wish to push URL X should call Push before sending any
    // data that may trigger a request for URL X. This avoids a race where the
    // client issues requests for X before receiving the PUSH_PROMISE for X.
    //
    // Push will run in a separate goroutine making the order of arrival
    // non-deterministic. Any required synchronization needs to be implemented
    // by the caller.
    //
    // Push returns ErrNotSupported if the client has disabled push or if push
    // is not supported on the underlying connection.
    Push(target string, opts *PushOptions) error
}

type Request

请求代表服务器接收或客户端发送的HTTP请求.

客户端和服务器使用情况之间的字段语义略有不同. 除以下字段上的注释外,请参阅Request.Write和RoundTripper的文档.

type Request struct {
    // Method specifies the HTTP method (GET, POST, PUT, etc.).
    // For client requests, an empty string means GET.
    //
    // Go's HTTP client does not support sending a request with
    // the CONNECT method. See the documentation on Transport for
    // details.
    Method string

    // URL specifies either the URI being requested (for server
    // requests) or the URL to access (for client requests).
    //
    // For server requests, the URL is parsed from the URI
    // supplied on the Request-Line as stored in RequestURI.  For
    // most requests, fields other than Path and RawQuery will be
    // empty. (See RFC 7230, Section 5.3)
    //
    // For client requests, the URL's Host specifies the server to
    // connect to, while the Request's Host field optionally
    // specifies the Host header value to send in the HTTP
    // request.
    URL *url.URL

    // The protocol version for incoming server requests.
    //
    // For client requests, these fields are ignored. The HTTP
    // client code always uses either HTTP/1.1 or HTTP/2.
    // See the docs on Transport for details.
    Proto      string // "HTTP/1.0"
    ProtoMajor int    // 1
    ProtoMinor int    // 0

    // Header contains the request header fields either received
    // by the server or to be sent by the client.
    //
    // If a server received a request with header lines,
    //
    //	Host: example.com
    //	accept-encoding: gzip, deflate
    //	Accept-Language: en-us
    //	fOO: Bar
    //	foo: two
    //
    // then
    //
    //	Header = map[string][]string{
    //		"Accept-Encoding": {"gzip, deflate"},
    //		"Accept-Language": {"en-us"},
    //		"Foo": {"Bar", "two"},
    //	}
    //
    // For incoming requests, the Host header is promoted to the
    // Request.Host field and removed from the Header map.
    //
    // HTTP defines that header names are case-insensitive. The
    // request parser implements this by using CanonicalHeaderKey,
    // making the first character and any characters following a
    // hyphen uppercase and the rest lowercase.
    //
    // For client requests, certain headers such as Content-Length
    // and Connection are automatically written when needed and
    // values in Header may be ignored. See the documentation
    // for the Request.Write method.
    Header Header

    // Body is the request's body.
    //
    // For client requests, a nil body means the request has no
    // body, such as a GET request. The HTTP Client's Transport
    // is responsible for calling the Close method.
    //
    // For server requests, the Request Body is always non-nil
    // but will return EOF immediately when no body is present.
    // The Server will close the request body. The ServeHTTP
    // Handler does not need to.
    Body io.ReadCloser

    // GetBody defines an optional func to return a new copy of
    // Body. It is used for client requests when a redirect requires
    // reading the body more than once. Use of GetBody still
    // requires setting Body.
    //
    // For server requests, it is unused.
    GetBody func() (io.ReadCloser, error) // Go 1.8

    // ContentLength records the length of the associated content.
    // The value -1 indicates that the length is unknown.
    // Values >= 0 indicate that the given number of bytes may
    // be read from Body.
    //
    // For client requests, a value of 0 with a non-nil Body is
    // also treated as unknown.
    ContentLength int64

    // TransferEncoding lists the transfer encodings from outermost to
    // innermost. An empty list denotes the "identity" encoding.
    // TransferEncoding can usually be ignored; chunked encoding is
    // automatically added and removed as necessary when sending and
    // receiving requests.
    TransferEncoding []string

    // Close indicates whether to close the connection after
    // replying to this request (for servers) or after sending this
    // request and reading its response (for clients).
    //
    // For server requests, the HTTP server handles this automatically
    // and this field is not needed by Handlers.
    //
    // For client requests, setting this field prevents re-use of
    // TCP connections between requests to the same hosts, as if
    // Transport.DisableKeepAlives were set.
    Close bool

    // For server requests, Host specifies the host on which the URL
    // is sought. Per RFC 7230, section 5.4, this is either the value
    // of the "Host" header or the host name given in the URL itself.
    // It may be of the form "host:port". For international domain
    // names, Host may be in Punycode or Unicode form. Use
    // golang.org/x/net/idna to convert it to either format if
    // needed.
    // To prevent DNS rebinding attacks, server Handlers should
    // validate that the Host header has a value for which the
    // Handler considers itself authoritative. The included
    // ServeMux supports patterns registered to particular host
    // names and thus protects its registered Handlers.
    //
    // For client requests, Host optionally overrides the Host
    // header to send. If empty, the Request.Write method uses
    // the value of URL.Host. Host may contain an international
    // domain name.
    Host string

    // Form contains the parsed form data, including both the URL
    // field's query parameters and the PATCH, POST, or PUT form data.
    // This field is only available after ParseForm is called.
    // The HTTP client ignores Form and uses Body instead.
    Form url.Values

    // PostForm contains the parsed form data from PATCH, POST
    // or PUT body parameters.
    //
    // This field is only available after ParseForm is called.
    // The HTTP client ignores PostForm and uses Body instead.
    PostForm url.Values // Go 1.1

    // MultipartForm is the parsed multipart form, including file uploads.
    // This field is only available after ParseMultipartForm is called.
    // The HTTP client ignores MultipartForm and uses Body instead.
    MultipartForm *multipart.Form

    // Trailer specifies additional headers that are sent after the request
    // body.
    //
    // For server requests, the Trailer map initially contains only the
    // trailer keys, with nil values. (The client declares which trailers it
    // will later send.)  While the handler is reading from Body, it must
    // not reference Trailer. After reading from Body returns EOF, Trailer
    // can be read again and will contain non-nil values, if they were sent
    // by the client.
    //
    // For client requests, Trailer must be initialized to a map containing
    // the trailer keys to later send. The values may be nil or their final
    // values. The ContentLength must be 0 or -1, to send a chunked request.
    // After the HTTP request is sent the map values can be updated while
    // the request body is read. Once the body returns EOF, the caller must
    // not mutate Trailer.
    //
    // Few HTTP clients, servers, or proxies support HTTP trailers.
    Trailer Header

    // RemoteAddr allows HTTP servers and other software to record
    // the network address that sent the request, usually for
    // logging. This field is not filled in by ReadRequest and
    // has no defined format. The HTTP server in this package
    // sets RemoteAddr to an "IP:port" address before invoking a
    // handler.
    // This field is ignored by the HTTP client.
    RemoteAddr string

    // RequestURI is the unmodified request-target of the
    // Request-Line (RFC 7230, Section 3.1.1) as sent by the client
    // to a server. Usually the URL field should be used instead.
    // It is an error to set this field in an HTTP client request.
    RequestURI string

    // TLS allows HTTP servers and other software to record
    // information about the TLS connection on which the request
    // was received. This field is not filled in by ReadRequest.
    // The HTTP server in this package sets the field for
    // TLS-enabled connections before invoking a handler;
    // otherwise it leaves the field nil.
    // This field is ignored by the HTTP client.
    TLS *tls.ConnectionState

    // Cancel is an optional channel whose closure indicates that the client
    // request should be regarded as canceled. Not all implementations of
    // RoundTripper may support Cancel.
    //
    // For server requests, this field is not applicable.
    //
    // Deprecated: Set the Request's context with NewRequestWithContext
    // instead. If a Request's Cancel field and context are both
    // set, it is undefined whether Cancel is respected.
    Cancel <-chan struct{} // Go 1.5

    // Response is the redirect response which caused this request
    // to be created. This field is only populated during client
    // redirects.
    Response *Response // Go 1.7
    // contains filtered or unexported fields
}

func NewRequest

func NewRequest(method, url string, body io.Reader) (*Request, error)

NewRequest使用背景上下文包装NewRequestWithContext.

func NewRequestWithContext 1.13

func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)

给定方法,URL和可选正文,NewRequestWithContext返回一个新的请求.

如果提供的正文也是io.Closer,则返回的Request.Body设置为body,并且将通过客户端方法Do,Post和PostForm以及Transport.RoundTrip关闭.

NewRequestWithContext返回适合与Client.Do或Transport.RoundTrip一起使用的请求. 要创建用于测试服务器处理程序的请求,请使用net / http / httptest程序包中的NewRequest函数,使用ReadRequest,或手动更新Request字段. 对于传出的客户端请求,上下文控制请求的整个生命周期及其响应:获取连接,发送请求以及读取响应标头和正文. 有关入站和出站请求字段之间的区别,请参见请求类型的文档.

如果body的类型为* bytes.Buffer,* bytes.Reader或* strings.Reader,则返回的请求的ContentLength设置为其确切值(而不是-1),将填充GetBody(因此307和308重定向可以重播body),如果ContentLength为0,则将Body设置为NoBody.

func ReadRequest

func ReadRequest(b *bufio.Reader) (*Request, error)

ReadRequest读取并解析来自b的传入请求.

ReadRequest是一个低级功能,仅应用于专业应用程序. 大多数代码应使用服务器读取请求并通过Handler接口处理请求. ReadRequest仅支持HTTP / 1.x请求. 对于HTTP / 2,请使用golang.org/x/net/http2.

func (*Request) AddCookie

func (r *Request) AddCookie(c *Cookie)

AddCookie将cookie添加到请求中. 根据RFC 6265第5.4节,AddCookie不会附加多个Cookie标头字段. 这意味着所有cookie(如果有的话)都写在同一行中,并用分号分隔.

func (*Request) BasicAuth 1.4

func (r *Request) BasicAuth() (username, password string, ok bool)

如果请求使用HTTP基本认证,则BasicAuth返回请求的Authorization标头中提供的用户名和密码. 参见RFC 2617,第2节.

func (*Request) Clone 1.13

func (r *Request) Clone(ctx context.Context) *Request

克隆返回r的深层副本,其上下文更改为ctx. 提供的ctx必须为非零.

对于传出的客户端请求,上下文控制请求的整个生命周期及其响应:获取连接,发送请求以及读取响应标头和正文.

func (*Request) Context 1.7

func (r *Request) Context() context.Context

上下文返回请求的上下文. 若要更改上下文,请使用WithContext.

返回的上下文始终为非零; 它默认为背景上下文.

对于传出的客户端请求,上下文控制取消.

对于传入的服务器请求,当客户端的连接关闭,请求被取消(使用HTTP / 2)或ServeHTTP方法返回时,上下文将被取消.

func (*Request) Cookie

func (r *Request) Cookie(name string) (*Cookie, error)

Cookie返回请求中提供的命名cookie,如果找不到,则返回ErrNoCookie. 如果多个Cookie与给定名称匹配,则仅返回一个Cookie.

func (*Request) Cookies

func (r *Request) Cookies() []*Cookie

Cookies解析并返回与请求一起发送的HTTP cookie.

func (*Request) FormFile

func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

FormFile返回提供的表单密钥的第一个文件. 如果需要,FormFile调用ParseMultipartForm和ParseForm.

func (*Request) FormValue

func (r *Request) FormValue(key string) string

FormValue返回查询的命名组件的第一个值. POST和PUT正文参数优先于URL查询字符串值. FormValue在必要时调用ParseMultipartForm和ParseForm,并忽略这些函数返回的任何错误. 如果键不存在,则FormValue返回空字符串. 要访问同一键的多个值,请调用ParseForm,然后直接检查Request.Form.

func (*Request) MultipartReader

func (r *Request) MultipartReader() (*multipart.Reader, error)

如果这是分段/表单数据或分段/混合POST请求,则MultipartReader返回MIME分段阅读器,否则返回nil和错误. 使用此函数代替ParseMultipartForm将请求主体作为流处理.

func (*Request) ParseForm

func (r *Request) ParseForm() error

ParseForm填充r.Form和r.PostForm.

对于所有请求,ParseForm都会从URL解析原始查询并更新r.Form.

对于POST,PUT和PATCH请求,它还将请求正文解析为一种形式,并将结果放入r.PostForm和r.Form中. 请求正文参数优先于r.Form中的URL查询字符串值.

对于其他HTTP方法,或者当Content-Type不是application / x-www-form-urlencoded时,不会读取请求正文,并且r.PostForm初始化为非null的空值.

如果请求正文的大小尚未受到MaxBytesReader的限制,则大小上限为10MB.

ParseMultipartForm自动调用ParseForm. ParseForm是幂等的.

func (*Request) ParseMultipartForm

func (r *Request) ParseMultipartForm(maxMemory int64) error

ParseMultipartForm将请求正文解析为multipart / form-data. 整个请求正文将被解析,其文件部分的最多maxMemory字节总共存储在内存中,其余部分存储在磁盘上的临时文件中. 如果需要,ParseMultipartForm调用ParseForm. 一次调用ParseMultipartForm之后,后续调用无效.

func (*Request) PostFormValue 1.1

func (r *Request) PostFormValue(key string) string

PostFormValue返回POST,PATCH或PUT请求主体的命名组件的第一个值. URL查询参数将被忽略. 如果需要,PostFormValue调用ParseMultipartForm和ParseForm,并忽略这些函数返回的任何错误. 如果键不存在,则PostFormValue返回空字符串.

func (*Request) ProtoAtLeast

func (r *Request) ProtoAtLeast(major, minor int) bool

ProtoAtLeast reports whether the HTTP protocol used in the request is at least major.minor.

func (*Request) Referer

func (r *Request) Referer() string

如果在请求中发送了引用,则引用将返回引用URL.

引荐来源网址拼写错误,就像请求本身一样,这是HTTP最早的错误. 该值也可以从Header映射中提取为Header [" Referer"];. 将其作为方法使用的好处是,编译器可以诊断使用备用(正确的英语)拼写req.Referrer()的程序,但不能诊断使用Header [" Referrer"]的程序.

func (*Request) SetBasicAuth

func (r *Request) SetBasicAuth(username, password string)

SetBasicAuth将请求的Authorization标头设置为使用HTTP基本身份验证以及提供的用户名和密码.

使用HTTP基本认证时,提供的用户名和密码未加密.

某些协议可能会对预转义用户名和密码提出其他要求. 例如,当与OAuth2一起使用时,两个参数都必须首先使用url.QueryEscape进行URL编码.

func (*Request) UserAgent

func (r *Request) UserAgent() string

如果在请求中发送了UserAgent,则返回客户端的User-Agent.

func (*Request) WithContext 1.7

func (r *Request) WithContext(ctx context.Context) *Request

WithContext返回r的浅表副本,其上下文更改为ctx. 提供的ctx必须为非零.

对于传出的客户端请求,上下文控制请求的整个生命周期及其响应:获取连接,发送请求以及读取响应标头和正文.

要使用上下文创建新请求,请使用NewRequestWithContext. 要更改请求(例如传入)的上下文,您还需要修改以发送出去,请使用Request.Clone. 在这两种用途之间,很少需要WithContext.

func (*Request) Write

func (r *Request) Write(w io.Writer) error

Write以有线格式写入HTTP / 1.1请求,即标头和正文. 此方法查询请求的以下字段:

Host
URL
Method (defaults to "GET")
Header
ContentLength
TransferEncoding
Body

如果存在"正文",则Content-Length为<= 0,并且TransferEncoding尚未设置为" identity",Write将" Transfer-Encoding:chunked"添加到标头. 发送后将其关闭.

func (*Request) WriteProxy

func (r *Request) WriteProxy(w io.Writer) error

WriteProxy类似于Write,但是以HTTP代理期望的形式写入请求. 特别是,WriteProxy根据RFC 7230的5.3节(包括方案和主机)用绝对URI写入请求的初始Request-URI行. 无论哪种情况,Wri​​teProxy都会使用r.Host或r.URL.Host写入Host标头.

type Response

响应表示来自HTTP请求的响应.

一旦收到响应标头,客户端和传输将从服务器返回响应. 在读取"正文"字段时,将按需流式传输响应正文.

type Response struct {
    Status     string // e.g. "200 OK"
    StatusCode int    // e.g. 200
    Proto      string // e.g. "HTTP/1.0"
    ProtoMajor int    // e.g. 1
    ProtoMinor int    // e.g. 0

    // Header maps header keys to values. If the response had multiple
    // headers with the same key, they may be concatenated, with comma
    // delimiters.  (RFC 7230, section 3.2.2 requires that multiple headers
    // be semantically equivalent to a comma-delimited sequence.) When
    // Header values are duplicated by other fields in this struct (e.g.,
    // ContentLength, TransferEncoding, Trailer), the field values are
    // authoritative.
    //
    // Keys in the map are canonicalized (see CanonicalHeaderKey).
    Header Header

    // Body represents the response body.
    //
    // The response body is streamed on demand as the Body field
    // is read. If the network connection fails or the server
    // terminates the response, Body.Read calls return an error.
    //
    // The http Client and Transport guarantee that Body is always
    // non-nil, even on responses without a body or responses with
    // a zero-length body. It is the caller's responsibility to
    // close Body. The default HTTP client's Transport may not
    // reuse HTTP/1.x "keep-alive" TCP connections if the Body is
    // not read to completion and closed.
    //
    // The Body is automatically dechunked if the server replied
    // with a "chunked" Transfer-Encoding.
    //
    // As of Go 1.12, the Body will also implement io.Writer
    // on a successful "101 Switching Protocols" response,
    // as used by WebSockets and HTTP/2's "h2c" mode.
    Body io.ReadCloser

    // ContentLength records the length of the associated content. The
    // value -1 indicates that the length is unknown. Unless Request.Method
    // is "HEAD", values >= 0 indicate that the given number of bytes may
    // be read from Body.
    ContentLength int64

    // Contains transfer encodings from outer-most to inner-most. Value is
    // nil, means that "identity" encoding is used.
    TransferEncoding []string

    // Close records whether the header directed that the connection be
    // closed after reading Body. The value is advice for clients: neither
    // ReadResponse nor Response.Write ever closes a connection.
    Close bool

    // Uncompressed reports whether the response was sent compressed but
    // was decompressed by the http package. When true, reading from
    // Body yields the uncompressed content instead of the compressed
    // content actually set from the server, ContentLength is set to -1,
    // and the "Content-Length" and "Content-Encoding" fields are deleted
    // from the responseHeader. To get the original response from
    // the server, set Transport.DisableCompression to true.
    Uncompressed bool // Go 1.7

    // Trailer maps trailer keys to values in the same
    // format as Header.
    //
    // The Trailer initially contains only nil values, one for
    // each key specified in the server's "Trailer" header
    // value. Those values are not added to Header.
    //
    // Trailer must not be accessed concurrently with Read calls
    // on the Body.
    //
    // After Body.Read has returned io.EOF, Trailer will contain
    // any trailer values sent by the server.
    Trailer Header

    // Request is the request that was sent to obtain this Response.
    // Request's Body is nil (having already been consumed).
    // This is only populated for Client requests.
    Request *Request

    // TLS contains information about the TLS connection on which the
    // response was received. It is nil for unencrypted responses.
    // The pointer is shared between responses and should not be
    // modified.
    TLS *tls.ConnectionState // Go 1.3
}

func Get

func Get(url string) (resp *Response, err error)

获取将GET发送到指定的URL. 如果响应是以下重定向代码之一,则Get将遵循该重定向,最多10个重定向:

301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)

如果重定向太多或HTTP协议错误,则返回错误. 非2xx响应不会导致错误. 返回的任何错误均为* url.Error类型. 如果请求超时或被取消,则url.Error值的Timeout方法将报告true.

当err为nil时,resp始终包含非nil resp.Body. 呼叫者完成阅读后,应关闭resp.Body.

Get是DefaultClient.Get的包装.

要使用自定义标头发出请求,请使用NewRequest和DefaultClient.Do.

Example

func Head(url string) (resp *Response, err error)

Head向指定的URL发出HEAD. 如果响应是以下重定向代码之一,则Head遵循该重定向,最多10个重定向:

301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)

Head是DefaultClient.Head的包装器

func Post

func Post(url, contentType string, body io.Reader) (resp *Response, err error)

Post发布POST到指定的URL.

呼叫者完成阅读后,应关闭resp.Body.

If the provided body is an io.Closer, it is closed after the request.

Post是DefaultClient.Post的包装.

若要设置自定义标头,请使用NewRequest和DefaultClient.Do.

有关如何处理重定向的详细信息,请参阅Client.Do方法文档.

func PostForm

func PostForm(url string, data url.Values) (resp *Response, err error)

PostForm向指定的URL发出POST,并将数据的键和值URL编码为请求正文.

Content-Type标头设置为application / x-www-form-urlencoded. 若要设置其他标头,请使用NewRequest和DefaultClient.Do.

当err为nil时,resp始终包含非nil resp.Body. 呼叫者完成阅读后,应关闭resp.Body.

PostForm是DefaultClient.PostForm的包装.

有关如何处理重定向的详细信息,请参阅Client.Do方法文档.

func ReadResponse

func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)

ReadResponse从r读取并返回HTTP响应. req参数可选地指定与此响应相对应的请求. 如果为零,则假定为GET请求. 阅读完resp.Body后,客户必须致电resp.Body.Close. 致电之后,客户可以检查预告片,以查找响应预告片中包含的键/值对.

func (*Response) Cookies

func (r *Response) Cookies() []*Cookie

Cookies解析并返回Set-Cookie标头中设置的cookie.

func (*Response) Location

func (r *Response) Location() (*url.URL, error)

位置返回响应的"位置"标头(如果存在)的URL. 相对重定向是相对于响应的请求来解决的. 如果不存在Location标头,则返回ErrNoLocation.

func (*Response) ProtoAtLeast

func (r *Response) ProtoAtLeast(major, minor int) bool

ProtoAtLeast报告响应中使用的HTTP协议是否至少为major.minor.

func (*Response) Write

func (r *Response) Write(w io.Writer) error

Write以HTTP / 1.x服务器响应格式将r写入w,包括状态行,标头,正文和可选的尾部.

此方法查询响应r的以下字段:

StatusCode
ProtoMajor
ProtoMinor
Request.Method
TransferEncoding
Trailer
Body
ContentLength
Header, values for non-canonical keys will have unpredictable behavior

发送后,响应主体将关闭.

type ResponseWriter

HTTP处理程序使用ResponseWriter接口构造HTTP响应.

返回Handler.ServeHTTP方法后,不得使用ResponseWriter.

type ResponseWriter interface {
    // Header returns the header map that will be sent by
    // WriteHeader. The Header map also is the mechanism with which
    // Handlers can set HTTP trailers.
    //
    // Changing the header map after a call to WriteHeader (or
    // Write) has no effect unless the modified headers are
    // trailers.
    //
    // There are two ways to set Trailers. The preferred way is to
    // predeclare in the headers which trailers you will later
    // send by setting the "Trailer" header to the names of the
    // trailer keys which will come later. In this case, those
    // keys of the Header map are treated as if they were
    // trailers. See the example. The second way, for trailer
    // keys not known to the Handler until after the first Write,
    // is to prefix the Header map keys with the TrailerPrefix
    // constant value. See TrailerPrefix.
    //
    // To suppress automatic response headers (such as "Date"), set
    // their value to nil.
    Header() Header

    // Write writes the data to the connection as part of an HTTP reply.
    //
    // If WriteHeader has not yet been called, Write calls
    // WriteHeader(http.StatusOK) before writing the data. If the Header
    // does not contain a Content-Type line, Write adds a Content-Type set
    // to the result of passing the initial 512 bytes of written data to
    // DetectContentType. Additionally, if the total size of all written
    // data is under a few KB and there are no Flush calls, the
    // Content-Length header is added automatically.
    //
    // Depending on the HTTP protocol version and the client, calling
    // Write or WriteHeader may prevent future reads on the
    // Request.Body. For HTTP/1.x requests, handlers should read any
    // needed request body data before writing the response. Once the
    // headers have been flushed (due to either an explicit Flusher.Flush
    // call or writing enough data to trigger a flush), the request body
    // may be unavailable. For HTTP/2 requests, the Go HTTP server permits
    // handlers to continue to read the request body while concurrently
    // writing the response. However, such behavior may not be supported
    // by all HTTP/2 clients. Handlers should read before writing if
    // possible to maximize compatibility.
    Write([]byte) (int, error)

    // WriteHeader sends an HTTP response header with the provided
    // status code.
    //
    // If WriteHeader is not called explicitly, the first call to Write
    // will trigger an implicit WriteHeader(http.StatusOK).
    // Thus explicit calls to WriteHeader are mainly used to
    // send error codes.
    //
    // The provided code must be a valid HTTP 1xx-5xx status code.
    // Only one header may be written. Go does not currently
    // support sending user-defined 1xx informational headers,
    // with the exception of 100-continue response header that the
    // Server sends automatically when the Request.Body is read.
    WriteHeader(statusCode int)
}

Example (Trailers)

HTTP尾部是一组键/值对,例如标头,位于HTTP响应之后而不是之前.

type RoundTripper

RoundTripper是表示执行单个HTTP事务,获取给定请求的响应的能力的接口.

RoundTripper必须安全,可以同时被多个goroutine使用.

type RoundTripper interface {
    // RoundTrip executes a single HTTP transaction, returning
    // a Response for the provided Request.
    //
    // RoundTrip should not attempt to interpret the response. In
    // particular, RoundTrip must return err == nil if it obtained
    // a response, regardless of the response's HTTP status code.
    // A non-nil err should be reserved for failure to obtain a
    // response. Similarly, RoundTrip should not attempt to
    // handle higher-level protocol details such as redirects,
    // authentication, or cookies.
    //
    // RoundTrip should not modify the request, except for
    // consuming and closing the Request's Body. RoundTrip may
    // read fields of the request in a separate goroutine. Callers
    // should not mutate or reuse the request until the Response's
    // Body has been closed.
    //
    // RoundTrip must always close the body, including on errors,
    // but depending on the implementation may do so in a separate
    // goroutine even after RoundTrip returns. This means that
    // callers wanting to reuse the body for subsequent requests
    // must arrange to wait for the Close call before doing so.
    //
    // The Request's URL and Header fields must be initialized.
    RoundTrip(*Request) (*Response, error)
}

DefaultTransport是Transport的默认实现,由DefaultClient使用. 它根据需要建立网络连接,并缓存它们以供后续调用重用. 它使用$ HTTP_PROXY和$ NO_PROXY(或$ http_proxy和$ no_proxy)环境变量指示的HTTP代理.

var DefaultTransport RoundTripper = &Transport{
    Proxy: ProxyFromEnvironment,
    DialContext: (&net.Dialer{
        Timeout:   30 * time.Second,
        KeepAlive: 30 * time.Second,
        DualStack: true,
    }).DialContext,
    ForceAttemptHTTP2:     true,
    MaxIdleConns:          100,
    IdleConnTimeout:       90 * time.Second,
    TLSHandshakeTimeout:   10 * time.Second,
    ExpectContinueTimeout: 1 * time.Second,
}

func NewFileTransport

func NewFileTransport(fs FileSystem) RoundTripper

NewFileTransport返回一个新的RoundTripper,服务于提供的FileSystem. 返回的RoundTripper会忽略传入请求中的URL主机以及该请求的大多数其他属性.

NewFileTransport的典型用例是在传输中注册"文件"协议,如下所示:

t := &http.Transport{}
t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
c := &http.Client{Transport: t}
res, err := c.Get("file:///etc/passwd")
...

type SameSite 1.11

SameSite允许服务器定义cookie属性,从而使浏览器无法将cookie与跨站点请求一起发送. 主要目标是减轻跨域信息泄漏的风险,并提供针对跨站点请求伪造攻击的某种保护.

有关详细信息,请参见https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 .

type SameSite int
const (
    SameSiteDefaultMode SameSite = iota + 1
    SameSiteLaxMode
    SameSiteStrictMode
    SameSiteNoneMode
)

type ServeMux

ServeMux是一个HTTP请求多路复用器. 它根据注册模式列表将每个传入请求的URL匹配,并为与URL最匹配的模式调用处理程序.

模式命名固定的,有根的路径(例如" /favicon.ico")或有根的子树(例如" / images /")(请注意在斜杠后面). 较长的模式优先于较短的模式,因此,如果同时为" / images /"和" / images / thumbnails /"注册了处理程序,则将为从" / images / thumbnails /"开始的路径调用后一个处理程序将在" / images /"子树中接收对任何其他路径的请求.

请注意,由于以斜杠结尾的模式命名了一个根目录子树,因此模式" /"与所有其他已注册模式不匹配的路径匹配,而不仅仅是Path ==" /"的URL.

如果已经注册了一个子树,并且接收到一个命名该子树根的请求而没有其后斜杠,则ServeMux将该请求重定向到该子树根(添加后斜杠). 可以用单独的路径注册来覆盖此行为,而不用斜杠结尾. 例如,注册" / images /"会使ServeMux将对" / images"的请求重定向到" / images /",除非已单独注册了" / images".

模式可以选择以主机名开头,仅将匹配项限制在该主机上. 特定于主机的模式优先于一般模式,因此处理程序可以注册" / codesearch"和" codesearch.google.com/"这两种模式,而无需同时接收对" http://www.google.com/ ".

ServeMux还负责清理URL请求路径和Host标头,清除端口号并重定向任何包含的请求. 或..元素,或重复的斜杠表示为等效的更干净的URL.

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

func NewServeMux

func NewServeMux() *ServeMux

NewServeMux分配并返回一个新的ServeMux.

func (*ServeMux) Handle

func (mux *ServeMux) Handle(pattern string, handler Handler)

Handle注册给定模式的处理程序. 如果已经存在用于模式的处理程序,则处理紧急情况.

Example

func (*ServeMux) HandleFunc

func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc注册给定模式的处理函数.

func (*ServeMux) Handler 1.1

func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)

处理程序返回用于给定请求的处理程序,请咨询r.Method,r.Host和r.URL.Path. 它总是返回一个非nil处理程序. 如果路径的格式不规范,则该处理程序将是内部生成的处理程序,该处理程序将重定向到规范路径. 如果主机包含端口,则在匹配处理程序时将忽略该端口.

路径和主机未更改用于CONNECT请求.

处理程序还会返回与请求匹配的已注册模式,如果是内部生成的重定向,则返回在跟随重定向之后将匹配的模式.

如果没有适用于该请求的注册处理程序,则处理程序返回"找不到页面"处理程序和空模式.

func (*ServeMux) ServeHTTP

func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)

ServeHTTP将请求调度到其模式与请求URL最匹配的处理程序.

type Server

服务器定义用于运行HTTP服务器的参数. 服务器的零值是有效配置.

type Server struct {
    Addr    string  // TCP address to listen on, ":http" if empty
    Handler Handler // handler to invoke, http.DefaultServeMux if nil

    // TLSConfig optionally provides a TLS configuration for use
    // by ServeTLS and ListenAndServeTLS. Note that this value is
    // cloned by ServeTLS and ListenAndServeTLS, so it's not
    // possible to modify the configuration with methods like
    // tls.Config.SetSessionTicketKeys. To use
    // SetSessionTicketKeys, use Server.Serve with a TLS Listener
    // instead.
    TLSConfig *tls.Config

    // ReadTimeout is the maximum duration for reading the entire
    // request, including the body.
    //
    // Because ReadTimeout does not let Handlers make per-request
    // decisions on each request body's acceptable deadline or
    // upload rate, most users will prefer to use
    // ReadHeaderTimeout. It is valid to use them both.
    ReadTimeout time.Duration

    // ReadHeaderTimeout is the amount of time allowed to read
    // request headers. The connection's read deadline is reset
    // after reading the headers and the Handler can decide what
    // is considered too slow for the body. If ReadHeaderTimeout
    // is zero, the value of ReadTimeout is used. If both are
    // zero, there is no timeout.
    ReadHeaderTimeout time.Duration // Go 1.8

    // WriteTimeout is the maximum duration before timing out
    // writes of the response. It is reset whenever a new
    // request's header is read. Like ReadTimeout, it does not
    // let Handlers make decisions on a per-request basis.
    WriteTimeout time.Duration

    // IdleTimeout is the maximum amount of time to wait for the
    // next request when keep-alives are enabled. If IdleTimeout
    // is zero, the value of ReadTimeout is used. If both are
    // zero, there is no timeout.
    IdleTimeout time.Duration // Go 1.8

    // MaxHeaderBytes controls the maximum number of bytes the
    // server will read parsing the request header's keys and
    // values, including the request line. It does not limit the
    // size of the request body.
    // If zero, DefaultMaxHeaderBytes is used.
    MaxHeaderBytes int

    // TLSNextProto optionally specifies a function to take over
    // ownership of the provided TLS connection when an NPN/ALPN
    // protocol upgrade has occurred. The map key is the protocol
    // name negotiated. The Handler argument should be used to
    // handle HTTP requests and will initialize the Request's TLS
    // and RemoteAddr if not already set. The connection is
    // automatically closed when the function returns.
    // If TLSNextProto is not nil, HTTP/2 support is not enabled
    // automatically.
    TLSNextProto map[string]func(*Server, *tls.Conn, Handler) // Go 1.1

    // ConnState specifies an optional callback function that is
    // called when a client connection changes state. See the
    // ConnState type and associated constants for details.
    ConnState func(net.Conn, ConnState) // Go 1.3

    // ErrorLog specifies an optional logger for errors accepting
    // connections, unexpected behavior from handlers, and
    // underlying FileSystem errors.
    // If nil, logging is done via the log package's standard logger.
    ErrorLog *log.Logger // Go 1.3

    // BaseContext optionally specifies a function that returns
    // the base context for incoming requests on this server.
    // The provided Listener is the specific Listener that's
    // about to start accepting requests.
    // If BaseContext is nil, the default is context.Background().
    // If non-nil, it must return a non-nil context.
    BaseContext func(net.Listener) context.Context // Go 1.13

    // ConnContext optionally specifies a function that modifies
    // the context used for a new connection c. The provided ctx
    // is derived from the base context and has a ServerContextKey
    // value.
    ConnContext func(ctx context.Context, c net.Conn) context.Context // Go 1.13
    // contains filtered or unexported fields
}

func (*Server) Close 1.8

func (srv *Server) Close() error

Close立即关闭所有活动的net.Listeners以及状态StateNew,StateActive或StateIdle中的所有连接. 要正常关机,请使用关机.

关闭不会尝试关闭(甚至不知道)任何被劫持的连接,例如WebSockets.

关闭返回从关闭服务器的基础侦听器返回的任何错误.

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe() error

ListenAndServe侦听TCP网络地址srv.Addr,然后调用Serve处理传入连接上的请求. 接受的连接配置为启用TCP保持活动状态.

如果srv.Addr为空,则使用":http".

ListenAndServe始终返回非nil错误. 关闭或关闭后,返回的错误为ErrServerClosed.

func (*Server) ListenAndServeTLS

func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error

ListenAndServeTLS侦听TCP网络地址srv.Addr,然后调用ServeTLS来处理传入TLS连接上的请求. 接受的连接配置为启用TCP保持活动状态.

如果未填充服务器的TLSConfig.Certificates或TLSConfig.GetCertificate,则必须提供包含证书和服务器匹配私钥的文件名. 如果证书是由证书颁发机构签名的,则certFile应该是服务器证书,任何中间件和CA证书的串联.

如果srv.Addr为空,则使用":https".

ListenAndServeTLS始终返回非null错误. 关闭或关闭后,返回的错误为ErrServerClosed.

func (*Server) RegisterOnShutdown 1.9

func (srv *Server) RegisterOnShutdown(f func())

RegisterOnShutdown注册一个函数来调用Shutdown. 这可用于正常关闭已进行NPN / ALPN协议升级或被劫持的连接. 此功能应启动特定于协议的正常关机,但不应等待关机完成.

func (*Server) Serve

func (srv *Server) Serve(l net.Listener) error

服务在侦听器l上接受传入连接,为每个连接创建一个新的服务goroutine. 服务goroutine读取请求,然后调用srv.Handler对其进行回复.

仅当侦听器返回* tls.Conn连接并且在TLS Config.NextProtos中将它们配置为" h2"时,才启用HTTP / 2支持.

服务始终返回非零错误并关闭l. 关闭或关闭后,返回的错误为ErrServerClosed.

func (*Server) ServeTLS 1.9

func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error

ServeTLS在侦听器l上接受传入连接,为每个连接创建一个新的服务goroutine. 服务goroutine会执行TLS设置,然后读取请求,并调用srv.Handler对其进行回复.

如果未填充服务器的TLSConfig.Certificates或TLSConfig.GetCertificate,则必须提供包含证书和服务器匹配私钥的文件. 如果证书是由证书颁发机构签名的,则certFile应该是服务器证书,任何中间件和CA证书的串联.

ServeTLS始终返回非nil错误. 关闭或关闭后,返回的错误为ErrServerClosed.

func (*Server) SetKeepAlivesEnabled 1.3

func (srv *Server) SetKeepAlivesEnabled(v bool)

SetKeepAlivesEnabled控制是否启用HTTP保持活动. 默认情况下,始终启用保持活动状态. 只有在资源非常有限的环境或正在关闭的服务器中才能禁用它们.

func (*Server) Shutdown 1.8

func (srv *Server) Shutdown(ctx context.Context) error

关机可以正常关闭服务器,而不会中断任何活动的连接. 关机的工作方式是先关闭所有打开的侦听器,然后关闭所有空闲连接,然后无限期等待连接返回到空闲状态然后关闭. 如果提供的上下文在关闭完成之前到期,则Shutdown返回上下文的错误,否则它将返回关闭服务器的基础侦听器所返回的任何错误.

调用Shutdown时,Serve,ListenAndServe和ListenAndServeTLS立即返回ErrServerClosed. 确保程序没有退出,而是等待关机返回.

关机不会尝试关闭也不等待被劫持的连接,例如WebSockets. 如果需要,Shutdown的调用者应单独通知此类长期存在的连接,并等待它们关闭. 有关注册关闭通知功能的方法,请参见RegisterOnShutdown.

一旦在服务器上调用了Shutdown,就可能无法重用它. 将来对诸如Serve之类的方法的调用将返回ErrServerClosed.

Example

type Transport

传输是RoundTripper的实现,它支持HTTP,HTTPS和HTTP代理(对于HTTP或带CONNECT的HTTPS).

默认情况下,传输缓存连接以供将来重用. 访问许多主机时,这可能会留下许多打开的连接. 可以使用Transport的CloseIdleConnections方法以及MaxIdleConnsPerHost和DisableKeepAlives字段来管理此行为.

传输应该重用,而不是根据需要创建. 传输程序可以安全地供多个goroutine并发使用.

传输是用于发出HTTP和HTTPS请求的低级原语. 有关Cookie和重定向之类的高级功能,请参阅客户端.

传输使用HTTP / 1.1作为HTTP URL,HTTP / 1.1或HTTP / 2作为HTTPS URL,这取决于服务器是否支持HTTP / 2,以及传输的配置方式. DefaultTransport支持HTTP / 2. 要在传输上显式启用HTTP / 2,请使用golang.org/x/net/http2并调用ConfigureTransport. 有关HTTP / 2的更多信息,请参见软件包文档.

状态码在1xx范围内的响应会自动处理(100个期望连续)或被忽略. 一个例外是HTTP状态代码101(交换协议),它被认为是终端状态,由RoundTrip返回. 若要查看被忽略的1xx响应,请使用httptrace跟踪包的ClientTrace.Got1xxResponse.

如果请求是幂等且没有主体或已定义其Request.GetBody,则传输仅在遇到网络错误时重试该请求. 如果HTTP请求具有HTTP方法GET,HEAD,OPTIONS或TRACE,则它们被认为是幂等的. 或者其标题映射包含" Idempotency-Key"或" X-Idempotency-Key"条目. 如果幂等性键值为零长度切片,则将请求视为幂等,但标头不会在线上发送.

type Transport struct {

    // Proxy specifies a function to return a proxy for a given
    // Request. If the function returns a non-nil error, the
    // request is aborted with the provided error.
    //
    // The proxy type is determined by the URL scheme. "http",
    // "https", and "socks5" are supported. If the scheme is empty,
    // "http" is assumed.
    //
    // If Proxy is nil or returns a nil *URL, no proxy is used.
    Proxy func(*Request) (*url.URL, error)

    // DialContext specifies the dial function for creating unencrypted TCP connections.
    // If DialContext is nil (and the deprecated Dial below is also nil),
    // then the transport dials using package net.
    //
    // DialContext runs concurrently with calls to RoundTrip.
    // A RoundTrip call that initiates a dial may end up using
    // a connection dialed previously when the earlier connection
    // becomes idle before the later DialContext completes.
    DialContext func(ctx context.Context, network, addr string) (net.Conn, error) // Go 1.7

    // Dial specifies the dial function for creating unencrypted TCP connections.
    //
    // Dial runs concurrently with calls to RoundTrip.
    // A RoundTrip call that initiates a dial may end up using
    // a connection dialed previously when the earlier connection
    // becomes idle before the later Dial completes.
    //
    // Deprecated: Use DialContext instead, which allows the transport
    // to cancel dials as soon as they are no longer needed.
    // If both are set, DialContext takes priority.
    Dial func(network, addr string) (net.Conn, error)

    // DialTLS specifies an optional dial function for creating
    // TLS connections for non-proxied HTTPS requests.
    //
    // If DialTLS is nil, Dial and TLSClientConfig are used.
    //
    // If DialTLS is set, the Dial hook is not used for HTTPS
    // requests and the TLSClientConfig and TLSHandshakeTimeout
    // are ignored. The returned net.Conn is assumed to already be
    // past the TLS handshake.
    DialTLS func(network, addr string) (net.Conn, error) // Go 1.4

    // TLSClientConfig specifies the TLS configuration to use with
    // tls.Client.
    // If nil, the default configuration is used.
    // If non-nil, HTTP/2 support may not be enabled by default.
    TLSClientConfig *tls.Config

    // TLSHandshakeTimeout specifies the maximum amount of time waiting to
    // wait for a TLS handshake. Zero means no timeout.
    TLSHandshakeTimeout time.Duration // Go 1.3

    // DisableKeepAlives, if true, disables HTTP keep-alives and
    // will only use the connection to the server for a single
    // HTTP request.
    //
    // This is unrelated to the similarly named TCP keep-alives.
    DisableKeepAlives bool

    // DisableCompression, if true, prevents the Transport from
    // requesting compression with an "Accept-Encoding: gzip"
    // request header when the Request contains no existing
    // Accept-Encoding value. If the Transport requests gzip on
    // its own and gets a gzipped response, it's transparently
    // decoded in the Response.Body. However, if the user
    // explicitly requested gzip it is not automatically
    // uncompressed.
    DisableCompression bool

    // MaxIdleConns controls the maximum number of idle (keep-alive)
    // connections across all hosts. Zero means no limit.
    MaxIdleConns int // Go 1.7

    // MaxIdleConnsPerHost, if non-zero, controls the maximum idle
    // (keep-alive) connections to keep per-host. If zero,
    // DefaultMaxIdleConnsPerHost is used.
    MaxIdleConnsPerHost int

    // MaxConnsPerHost optionally limits the total number of
    // connections per host, including connections in the dialing,
    // active, and idle states. On limit violation, dials will block.
    //
    // Zero means no limit.
    MaxConnsPerHost int // Go 1.11

    // IdleConnTimeout is the maximum amount of time an idle
    // (keep-alive) connection will remain idle before closing
    // itself.
    // Zero means no limit.
    IdleConnTimeout time.Duration // Go 1.7

    // ResponseHeaderTimeout, if non-zero, specifies the amount of
    // time to wait for a server's response headers after fully
    // writing the request (including its body, if any). This
    // time does not include the time to read the response body.
    ResponseHeaderTimeout time.Duration // Go 1.1

    // ExpectContinueTimeout, if non-zero, specifies the amount of
    // time to wait for a server's first response headers after fully
    // writing the request headers if the request has an
    // "Expect: 100-continue" header. Zero means no timeout and
    // causes the body to be sent immediately, without
    // waiting for the server to approve.
    // This time does not include the time to send the request header.
    ExpectContinueTimeout time.Duration // Go 1.6

    // TLSNextProto specifies how the Transport switches to an
    // alternate protocol (such as HTTP/2) after a TLS NPN/ALPN
    // protocol negotiation. If Transport dials an TLS connection
    // with a non-empty protocol name and TLSNextProto contains a
    // map entry for that key (such as "h2"), then the func is
    // called with the request's authority (such as "example.com"
    // or "example.com:1234") and the TLS connection. The function
    // must return a RoundTripper that then handles the request.
    // If TLSNextProto is not nil, HTTP/2 support is not enabled
    // automatically.
    TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper // Go 1.6

    // ProxyConnectHeader optionally specifies headers to send to
    // proxies during CONNECT requests.
    ProxyConnectHeader Header // Go 1.8

    // MaxResponseHeaderBytes specifies a limit on how many
    // response bytes are allowed in the server's response
    // header.
    //
    // Zero means to use a default limit.
    MaxResponseHeaderBytes int64 // Go 1.7

    // WriteBufferSize specifies the size of the write buffer used
    // when writing to the transport.
    // If zero, a default (currently 4KB) is used.
    WriteBufferSize int // Go 1.13

    // ReadBufferSize specifies the size of the read buffer used
    // when reading from the transport.
    // If zero, a default (currently 4KB) is used.
    ReadBufferSize int // Go 1.13

    // ForceAttemptHTTP2 controls whether HTTP/2 is enabled when a non-zero
    // Dial, DialTLS, or DialContext func or TLSClientConfig is provided.
    // By default, use of any those fields conservatively disables HTTP/2.
    // To use a custom dialer or TLS config and still attempt HTTP/2
    // upgrades, set this to true.
    ForceAttemptHTTP2 bool // Go 1.13
    // contains filtered or unexported fields
}

func (*Transport) CancelRequest 1.1

func (t *Transport) CancelRequest(req *Request)

CancelRequest通过关闭其连接来取消进行中的请求. 只有在RoundTrip返回后才调用CancelRequest.

不建议使用:使用Request.WithContext创建具有可取消上下文的请求. CancelRequest无法取消HTTP / 2请求.

func (*Transport) Clone 1.13

func (t *Transport) Clone() *Transport

克隆返回t导出字段的深层副本.

func (*Transport) CloseIdleConnections

func (t *Transport) CloseIdleConnections()

CloseIdleConnections关闭先前与先前请求连接的所有连接,但现在处于"保持活动"状态的空闲连接. 它不会中断当前正在使用的任何连接.

func (*Transport) RegisterProtocol

func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)

RegisterProtocol使用方案注册新协议. 传输将使用给定方案将请求传递给rt. 模拟HTTP请求语义是rt的责任.

其他包可以使用RegisterProtocol提供协议方案的实现,例如" ftp"或" file".

如果rt.RoundTrip返回ErrSkipAltProtocol,则传输将为该请求处理RoundTrip本身,就像未注册协议一样.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *Request) (*Response, error)

RoundTrip实现RoundTripper接口.

有关更高级别的HTTP客户端支持(例如cookie和重定向的处理),请参阅Get,Post和Client类型.

与RoundTripper界面类似,RoundTrip返回的错误类型未指定.

Subdirectories

Name Synopsis
..
cgi 包cgi实现RFC 3875中指定的CGI(通用网关接口).
cookiejar 程序包cookiejar实现了与RFC 6265兼容的内存中http.CookieJar.
fcgi 软件包fcgi实现了FastCGI协议.
httptest 包httptest提供了用于HTTP测试的实用程序.
httptrace 包httptrace提供了跟踪HTTP客户端请求中的事件的机制.
httputil 包httputil提供了HTTP实用程序功能,补充了net / http包中更常见的功能.
pprof 包pprof通过其HTTP服务器运行时性能分析数据提供pprof可视化工具所需的格式.

by  ICOPY.SITE