Version: v1.2.0 Latest Latest

This package is not in the latest version of its module.

Go to latest
Published: Jun 21, 2021 License: Apache-2.0 Imports: 28 Imported by: 0



Copyright 2010 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.



View Source
const (
	StatusContinue           = 100
	StatusSwitchingProtocols = 101

	StatusOK                   = 200
	StatusCreated              = 201
	StatusAccepted             = 202
	StatusNonAuthoritativeInfo = 203
	StatusNoContent            = 204
	StatusResetContent         = 205
	StatusPartialContent       = 206

	StatusMultipleChoices   = 300
	StatusMovedPermanently  = 301
	StatusFound             = 302
	StatusSeeOther          = 303
	StatusNotModified       = 304
	StatusUseProxy          = 305
	StatusTemporaryRedirect = 307

	StatusBadRequest                   = 400
	StatusUnauthorized                 = 401
	StatusPaymentRequired              = 402
	StatusForbidden                    = 403
	StatusNotFound                     = 404
	StatusMethodNotAllowed             = 405
	StatusNotAcceptable                = 406
	StatusProxyAuthRequired            = 407
	StatusRequestTimeout               = 408
	StatusConflict                     = 409
	StatusGone                         = 410
	StatusLengthRequired               = 411
	StatusPreconditionFailed           = 412
	StatusRequestEntityTooLarge        = 413
	StatusRequestURITooLong            = 414
	StatusUnsupportedMediaType         = 415
	StatusRequestedRangeNotSatisfiable = 416
	StatusExpectationFailed            = 417
	StatusTeapot                       = 418

	StatusInternalServerError     = 500
	StatusNotImplemented          = 501
	StatusBadGateway              = 502
	StatusServiceUnavailable      = 503
	StatusGatewayTimeout          = 504
	StatusHTTPVersionNotSupported = 505

HTTP status codes, defined in RFC 2616.

View Source
const DefaultMaxHeaderBytes = 1 << 20 // 1 MB

DefaultMaxHeaderBytes is the maximum permitted size of the headers in an HTTP request. This can be overridden by setting config.MaxHeaderBytes.

View Source
const DefaultMaxHeaderUriBytes = 8 * 1024

DefaultMaxHeaderUriBytes is the maximum permitted size of URI in headers in an HTTP request. This can be overridden by setting config.MaxHeaderUriBytes.

View Source
const DefaultMaxIdleConnsPerHost = 2

DefaultMaxIdleConnsPerHost is the default value of Transport's MaxIdleConnsPerHost.

View Source
const (
	MaxUriSize = 1024 * 64
View Source
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"

TimeFormat is the time format to use with time.Parse and time.Time.Format when parsing or generating times in HTTP headers. It is like time.RFC1123 but hard codes GMT as the time zone.


View Source
var (
	ErrHeaderTooLong        = &ProtocolError{"header too long"}
	ErrShortBody            = &ProtocolError{"entity body too short"}
	ErrNotSupported         = &ProtocolError{"feature not supported"}
	ErrUnexpectedTrailer    = &ProtocolError{"trailer header without chunked transfer encoding"}
	ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"}
	ErrNotMultipart         = &ProtocolError{"request Content-Type isn't multipart/form-data"}
	ErrMissingBoundary      = &ProtocolError{"no multipart boundary param in Content-Type"}
View Source
var EofReader = &struct {

EofReader is a non-nil io.ReadCloser that always returns EOF. It embeds a *strings.Reader so it still has a WriteTo method and io.Copy won't need a buffer.

View Source
var ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
View Source
var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")

ErrBodyReadAfterClose is returned when reading a Request or Response Body after the body has been closed. This typically happens when the body is read after an HTTP Handler calls WriteHeader or Write on its ResponseWriter.

View Source
var ErrLineTooLong = errors.New("header line too long")
View Source
var ErrMissingFile = errors.New("http: no such file")

ErrMissingFile is returned by FormFile when the provided file field name is either not present in the request or not a file field.

View Source
var ErrNoCookie = errors.New("http: named cookie not present")
View Source
var ErrNoLocation = errors.New("http: no Location header in response")
View Source
var StatusText = map[int]string{
	StatusContinue:           "Continue",
	StatusSwitchingProtocols: "Switching Protocols",

	StatusOK:                   "OK",
	StatusCreated:              "Created",
	StatusAccepted:             "Accepted",
	StatusNonAuthoritativeInfo: "Non-Authoritative Information",
	StatusNoContent:            "No Content",
	StatusResetContent:         "Reset Content",
	StatusPartialContent:       "Partial Content",

	StatusMultipleChoices:   "Multiple Choices",
	StatusMovedPermanently:  "Moved Permanently",
	StatusFound:             "Found",
	StatusSeeOther:          "See Other",
	StatusNotModified:       "Not Modified",
	StatusUseProxy:          "Use Proxy",
	StatusTemporaryRedirect: "Temporary Redirect",

	StatusBadRequest:                   "Bad Request",
	StatusUnauthorized:                 "Unauthorized",
	StatusPaymentRequired:              "Payment Required",
	StatusForbidden:                    "Forbidden",
	StatusNotFound:                     "Not Found",
	StatusMethodNotAllowed:             "Method Not Allowed",
	StatusNotAcceptable:                "Not Acceptable",
	StatusProxyAuthRequired:            "Proxy Authentication Required",
	StatusRequestTimeout:               "Request Timeout",
	StatusConflict:                     "Conflict",
	StatusGone:                         "Gone",
	StatusLengthRequired:               "Length Required",
	StatusPreconditionFailed:           "Precondition Failed",
	StatusRequestEntityTooLarge:        "Request Entity Too Large",
	StatusRequestURITooLong:            "Request URI Too Long",
	StatusUnsupportedMediaType:         "Unsupported Media Type",
	StatusRequestedRangeNotSatisfiable: "Requested Range Not Satisfiable",
	StatusExpectationFailed:            "Expectation Failed",
	StatusTeapot:                       "I'm a teapot",

	StatusInternalServerError:     "Internal Server Error",
	StatusNotImplemented:          "Not Implemented",
	StatusBadGateway:              "Bad Gateway",
	StatusServiceUnavailable:      "Service Unavailable",
	StatusGatewayTimeout:          "Gateway Timeout",
	StatusHTTPVersionNotSupported: "HTTP Version Not Supported",
	// contains filtered or unexported fields


func CanonicalHeaderKey

func CanonicalHeaderKey(s string) string

CanonicalHeaderKey returns the canonical format of the header key s. The canonicalization converts the first letter and any letter following a hyphen to upper case; the rest are converted to lowercase. For example, the canonical key for "accept-encoding" is "Accept-Encoding".

func CopyHeader

func CopyHeader(dst, src Header)

func DetectContentType

func DetectContentType(data []byte) string

DetectContentType implements the algorithm described at to determine the Content-Type of the given data. It considers at most the first 512 bytes of data. DetectContentType always returns a valid MIME type: if it cannot determine a more specific one, it returns "application/octet-stream".

func Error

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

Error replies to the request with the specified error message and HTTP code. The error message should be plain text.

func HasToken

func HasToken(v, token string) bool

HasToken reports whether token appears with v, ASCII case-insensitive, with space or comma boundaries. token must be all lowercase. v may contain mixed cased.

func MaxBytesReader

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

MaxBytesReader is similar to io.LimitReader but is intended for limiting the size of incoming request bodies. In contrast to io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a non-EOF error for a Read beyond the limit, and Closes the underlying reader when its Close method is called.

MaxBytesReader prevents clients from accidentally or maliciously sending a large request and wasting server resources.

func ParseHTTPVersion

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

ParseHTTPVersion parses a HTTP version string. "HTTP/1.0" returns (1, 0, true).

func ParseTime

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

ParseTime parses a time header (such as the Date: header), trying each of the three formats allowed by HTTP/1.1: TimeFormat, time.RFC850, and time.ANSIC.

func ProxyFromEnvironment

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

ProxyFromEnvironment returns the URL of the proxy to use for a given request, as indicated by the environment variables $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy). An error is returned if the proxy environment is invalid. 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.

func ProxyURL

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

ProxyURL returns a proxy function (for use in a Transport) that always returns the same URL.

func SetCookie

func SetCookie(w ResponseWriter, cookie *Cookie)

SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers.

func SetDisableSanitize

func SetDisableSanitize(disabled bool)

func StatusTextGet

func StatusTextGet(code int) string

StatusTextGet returns a text for the HTTP status code. It returns the empty string if the code is unknown.


type CloseNotifier

type CloseNotifier interface {
	// CloseNotify returns a channel that receives a single value
	// when the client connection has gone away.
	CloseNotify() <-chan bool

The CloseNotifier interface is implemented by ResponseWriters which allow detecting when the underlying connection has gone away.

This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready.

type CloseWatcher

type CloseWatcher struct {
	// contains filtered or unexported fields

CloseWatcher can be used to cancel long operations on the server if the client has disconnected.

func NewCloseWatcher

func NewCloseWatcher(notifier CloseNotifier, onClose func()) *CloseWatcher

func (*CloseWatcher) Stop

func (w *CloseWatcher) Stop()

func (*CloseWatcher) WatchLoop

func (w *CloseWatcher) WatchLoop()

type ConnState

type ConnState int

A ConnState represents the state of a client connection to a server. It's used by the optional Server.ConnState hook.

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.

	// 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.

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

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

func (ConnState) String

func (c ConnState) String() string

type ConnectError

type ConnectError struct {
	Addr string
	Err  error

func (ConnectError) Error

func (e ConnectError) Error() string
type Cookie struct {
	Name       string
	Value      string
	Path       string
	Domain     string
	Expires    time.Time
	RawExpires string

	// 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
	Raw      string
	Unparsed []string // Raw text of unparsed attribute-value pairs

A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an HTTP response or the Cookie header of an HTTP request.

func (*Cookie) String

func (c *Cookie) String() string

String returns the serialization of the cookie for use in a Cookie header (if only Name and Value are set) or a Set-Cookie response header (if other fields are set).

type CookieMap

type CookieMap map[string]*Cookie

func CookieMapGet

func CookieMapGet(cookies []*Cookie) CookieMap

CookieMapGet parse cookies(slice) to req.Route.CookieMap(map)

func (CookieMap) Get

func (cm CookieMap) Get(key string) (*Cookie, bool)

type FlowLimiter

type FlowLimiter interface {
	// check whether current connection should be accept or not
	AcceptConn() bool

	// check whether current request should be accept or not
	AcceptRequest() bool

type Flusher

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

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

Note that even for ResponseWriters that support Flush, if the client is connected through an HTTP proxy, the buffered data may not reach the client until the response completes.

type Handler

type Handler interface {
	ServeHTTP(ResponseWriter, *Request)

Objects implementing the Handler interface can be registered to serve a particular path or subtree in the HTTP server.

ServeHTTP should write reply headers and data to the ResponseWriter and then return. Returning signals that the request is finished and that the HTTP server can move on to the next request on the connection.

type HandlerFunc

type HandlerFunc func(ResponseWriter, *Request)

The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler object that calls f.

func (HandlerFunc) ServeHTTP

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

ServeHTTP calls f(w, r).

type Header map[string][]string

A Header represents the key-value pairs in an HTTP header.

func (Header) Add

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

Add adds the key, value pair to the header. It appends to any existing values associated with key.

func (Header) Clone

func (h Header) Clone() Header

func (Header) Del

func (h Header) Del(key string)

Del deletes the values associated with key.

func (Header) Get

func (h Header) Get(key string) string

Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". To access multiple values of a key, access the map directly with CanonicalHeaderKey.

func (Header) GetDirect

func (h Header) GetDirect(key string) string

GetDirect gets the value associated with the given key in CanonicalHeaderKey form.

func (Header) Keys

func (h Header) Keys() []string

Keys get all keys from header

func (Header) Set

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

Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key.

func (Header) Values

func (h Header) Values(key string) []string

Values returns all values associated with the given key. It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. To use non-canonical keys, access the map directly. The returned slice is not a copy.

func (Header) Write

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

Write writes a header in wire format.

func (Header) WriteSubset

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

WriteSubset writes a header in wire format. If exclude is not nil, keys where exclude[key] == true are not written.

type 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.
	Hijack() (net.Conn, *bufio.ReadWriter, error)

type HttpState

type HttpState struct {
	HttpBackendConnAll       *metrics.Counter
	HttpBackendConnSucc      *metrics.Counter
	HttpBackendReqAll        *metrics.Counter
	HttpBackendReqSucc       *metrics.Counter
	HttpCancelOnClientClose  *metrics.Counter
	HttpPanicBackendRead     *metrics.Counter
	HttpPanicBackendWrite    *metrics.Counter
	HttpPanicClientFlushLoop *metrics.Counter
	HttpPanicClientWatchLoop *metrics.Counter

func GetHttpState

func GetHttpState() *HttpState

type MaxLatencyWriter

type MaxLatencyWriter struct {
	// contains filtered or unexported fields

func NewMaxLatencyWriter

func NewMaxLatencyWriter(dst WriteFlusher, latency time.Duration,
	onExitFlushLoop func()) *MaxLatencyWriter

func (*MaxLatencyWriter) Flush

func (m *MaxLatencyWriter) Flush() error

func (*MaxLatencyWriter) FlushLoop

func (m *MaxLatencyWriter) FlushLoop()

func (*MaxLatencyWriter) Stop

func (m *MaxLatencyWriter) Stop()

func (*MaxLatencyWriter) Write

func (m *MaxLatencyWriter) Write(p []byte) (int, error)

type Peeker

type Peeker interface {
	Peek(n int) ([]byte, error)

common interface for peeking data

type ProtocolError

type ProtocolError struct {
	ErrorString string

HTTP request parsing errors.

func (*ProtocolError) Error

func (err *ProtocolError) Error() string

type ReadRespHeaderError

type ReadRespHeaderError struct {
	Err error

func (ReadRespHeaderError) Error

func (e ReadRespHeaderError) Error() string

type Request

type Request struct {
	Method string // GET, POST, PUT, etc.

	// URL is created 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 2616, Section 5.1.2)
	URL *url.URL

	// The protocol version for incoming requests.
	// Outgoing requests always use HTTP/1.1.
	Proto      string // "HTTP/1.0"
	ProtoMajor int    // 1
	ProtoMinor int    // 0

	// A header maps request lines to their values.
	// If the header says
	//	accept-encoding: gzip, deflate
	//	Accept-Language: en-us
	//	Connection: keep-alive
	// then
	//	Header = map[string][]string{
	//		"Accept-Encoding": {"gzip, deflate"},
	//		"Accept-Language": {"en-us"},
	//		"Connection": {"keep-alive"},
	//	}
	// HTTP defines that header names are case-insensitive.
	// The request parser implements this by canonicalizing the
	// name, making the first character and any characters
	// following a hyphen uppercase and the rest lowercase.
	Header Header

	// a headerKeys represents keys of header in original order
	HeaderKeys textproto.MIMEKeys

	// 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

	// 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 outgoing requests, a value of 0 means unknown if Body is not nil.
	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.
	Close bool

	// The host on which the URL is sought.
	// Per RFC 2616, 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".
	Host string

	// Form contains the parsed form data, including both the URL
	// field's query parameters and the 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 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

	// 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 maps trailer keys to values.  Like for Header, if the
	// response has multiple trailer lines with the same key, they will be
	// concatenated, delimited by commas.
	// For server requests, Trailer is only populated after Body has been
	// closed or fully consumed.
	// Trailer support is only partially complete.
	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-URI of the
	// Request-Line (RFC 2616, Section 5.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 *bfe_tls.ConnectionState

	// State allows HTTP server and other software to record
	// information about the request. This filed may be not filled.
	State *RequestState

A Request represents an HTTP request received by a server or to be sent by a client.

func NewRequest

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

NewRequest returns a new Request given a method, URL, and optional body.

If the provided body is also an io.Closer, the returned Request.Body is set to body and will be closed by the Client methods Do, Post, and PostForm, and Transport.RoundTrip.

func ReadRequest

func ReadRequest(b *bfe_bufio.Reader, maxUriBytes int) (req *Request, err error)

ReadRequest reads and parses a request from b.

func (*Request) AddCookie

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

AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, AddCookie does not attach more than one Cookie header field. That means all cookies, if any, are written into the same line, separated by semicolon.

func (*Request) BasicAuth

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

BasicAuth returns the username and password provided in the request's Authorization header, if the request uses HTTP Basic Authentication. See RFC 2617, Section 2.

func (*Request) Cookie

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

Cookie returns the named cookie provided in the request or ErrNoCookie if not found.

func (*Request) Cookies

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

Cookies parses and returns the HTTP cookies sent with the request.

func (*Request) ExpectsContinue

func (r *Request) ExpectsContinue() bool

func (*Request) FormFile

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

FormFile returns the first file for the provided form key. FormFile calls ParseMultipartForm and ParseForm if necessary.

func (*Request) FormValue

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

FormValue returns the first value for the named component of the query. POST and PUT body parameters take precedence over URL query string values. FormValue calls ParseMultipartForm and ParseForm if necessary. To access multiple values of the same key use ParseForm.

func (*Request) MultipartReader

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

MultipartReader returns a MIME multipart reader if this is a multipart/form-data POST request, else returns nil and an error. Use this function instead of ParseMultipartForm to process the request body as a stream.

func (*Request) ParseForm

func (r *Request) ParseForm() error

ParseForm parses the raw query from the URL and updates r.Form.

For POST or PUT requests, it also parses the request body as a form and put the results into both r.PostForm and r.Form. POST and PUT body parameters take precedence over URL query string values in r.Form.

If the request Body's size has not already been limited by MaxBytesReader, the size is capped at 10MB.

ParseMultipartForm calls ParseForm automatically. It is idempotent.

func (*Request) ParseMultipartForm

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

ParseMultipartForm parses a request body as multipart/form-data. The whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory, with the remainder stored on disk in temporary files. ParseMultipartForm calls ParseForm if necessary. After one call to ParseMultipartForm, subsequent calls have no effect.

func (*Request) PostFormValue

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

PostFormValue returns the first value for the named component of the POST or PUT request body. URL query parameters are ignored. PostFormValue calls ParseMultipartForm and ParseForm if necessary.

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

Referer returns the referring URL, if sent in the request.

Referer is misspelled as in the request itself, a mistake from the earliest days of HTTP. This value can also be fetched from the Header map as Header["Referer"]; the benefit of making it available as a method is that the compiler can diagnose programs that use the alternate (correct English) spelling req.Referrer() but cannot diagnose programs that use Header["Referrer"].

func (*Request) SetBasicAuth

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

SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.

With HTTP Basic Authentication the provided username and password are not encrypted.

func (*Request) UserAgent

func (r *Request) UserAgent() string

UserAgent returns the client's User-Agent, if sent in the request.

func (*Request) WantsClose

func (r *Request) WantsClose() bool

func (*Request) WantsHttp10KeepAlive

func (r *Request) WantsHttp10KeepAlive() bool

func (*Request) Write

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

Write writes an HTTP/1.1 request -- header and body -- in wire format. This method consults the following fields of the request:

Method (defaults to "GET")

If Body is present, Content-Length is <= 0 and TransferEncoding hasn't been set to "identity", Write adds "Transfer-Encoding: chunked" to the header. Body is closed after it is sent.

func (*Request) WriteProxy

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

WriteProxy is like Write but writes the request in the form expected by an HTTP proxy. In particular, WriteProxy writes the initial Request-URI line of the request with an absolute URI, per section 5.1.2 of RFC 2616, including the scheme and host. In either case, WriteProxy also writes a Host header, using either r.Host or r.URL.Host.

type RequestState

type RequestState struct {
	// SerialNumber identify Nth request on one connection
	// this field of first request is 1, second is 2, and so on
	SerialNumber uint32

	// Conn is the connection from which request arrived
	Conn net.Conn

	// StartTime is the time when the first byte of request header was
	// received. StartTime may be approximate.
	StartTime time.Time

	// ConnectBackendStart is the time when start get a connection
	ConnectBackendStart time.Time

	// ConnectBackendEnd is the time when got a connection(may got from connection pool)
	ConnectBackendEnd time.Time

	// HeaderSize is the size of the request header.
	HeaderSize uint32

	// BodySize is the size of request body.
	BodySize uint32

type RespHeaderTimeoutError

type RespHeaderTimeoutError struct{}

func (RespHeaderTimeoutError) Error

func (e RespHeaderTimeoutError) Error() string

type Response

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.  (Section 4.2 of RFC 2616 requires that multiple headers
	// be semantically equivalent to a comma-delimited sequence.) Values
	// duplicated by other fields in this struct (e.g., ContentLength) are
	// omitted from Header.
	// Keys in the map are canonicalized (see CanonicalHeaderKey).
	Header Header

	// Body represents the response body.
	// The http Client and Transport guarantee that Body is always
	// non-nil, even on responses without a body or responses with
	// a zero-lengthed body.
	// The Body is automatically dechunked if the server replied
	// with a "chunked" Transfer-Encoding.
	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

	// Signer calculate signature for response
	Signer SignCalculater

	// 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

	// Trailer maps trailer keys to values, in the same
	// format as the header.
	Trailer Header

	H2Trailer *http.Header

	// 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 *bfe_tls.ConnectionState

Response represents the response from an HTTP request.

func ReadResponse

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

ReadResponse reads and returns an HTTP response from r. The req parameter optionally specifies the Request that corresponds to this Response. If nil, a GET request is assumed. Clients must call resp.Body.Close when finished reading resp.Body. After that call, clients can inspect resp.Trailer to find key/value pairs included in the response trailer.

func (*Response) Cookies

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

Cookies parses and returns the cookies set in the Set-Cookie headers.

func (*Response) Location

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

Location returns the URL of the response's "Location" header, if present. Relative redirects are resolved relative to the Response's Request. ErrNoLocation is returned if no Location header is present.

func (*Response) ProtoAtLeast

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

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

func (*Response) Write

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

Writes the response (header, body and trailer) in wire format. This method consults the following fields of the response:

Header, values for non-canonical keys will have unpredictable behavior

type ResponseWriter

type ResponseWriter interface {
	// Header returns the header map that will be sent by WriteHeader.
	// Changing the header after a call to WriteHeader (or Write) has
	// no effect.
	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.
	Write([]byte) (int, error)

	// WriteHeader sends an HTTP response header with 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.

A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.

type RoundTripper

type RoundTripper interface {
	// RoundTrip executes a single HTTP transaction, returning
	// the Response for the request req.  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 Body. The request's URL and
	// Header fields are guaranteed to be initialized.
	RoundTrip(*Request) (*Response, error)

RoundTripper is an interface representing the ability to execute a single HTTP transaction, obtaining the Response for a given Request.

A RoundTripper must be safe for concurrent use by multiple goroutines.

var DefaultTransport RoundTripper = &Transport{Proxy: ProxyFromEnvironment}

DefaultTransport is the default implementation of Transport and is used by DefaultClient. It establishes network connections as needed and caches them for reuse by subsequent calls. It uses HTTP proxies as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy) environment variables.

type SameSite

type SameSite int

SameSite allows a server to define a cookie attribute making it impossible for the browser to send this cookie along with cross-site requests. The main goal is to mitigate the risk of cross-origin information leakage, and provide some protection against cross-site request forgery attacks.

See for details.

const (
	SameSiteDefaultMode SameSite = iota + 1

type Server

type Server struct {
	Addr                    string        // TCP address to listen on, ":http" if empty
	Handler                 Handler       // handler to invoke, http.DefaultServeMux if nil
	ReadTimeout             time.Duration // maximum duration before timing out read of the request
	WriteTimeout            time.Duration // maximum duration before timing out write of the response
	TlsHandshakeTimeout     time.Duration // maximum duration before timing out handshake
	GracefulShutdownTimeout time.Duration // maximum duration before timing out graceful shutdown
	MaxHeaderBytes          int           // maximum size of request headers, DefaultMaxHeaderBytes if 0
	MaxHeaderUriBytes       int           // max URI(in header) length in bytes in request
	TLSConfig               *tls.Config   // optional TLS config, used by ListenAndServeTLS

	// TLSNextProto optionally specifies a function to take over
	// ownership of the provided TLS connection when an NPN
	// 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.
	TLSNextProto map[string]func(*Server, *tls.Conn, Handler)

	// HTTPNextProto optionally specifies a function to take over
	// ownership of the http connection when an HTTP Upgrade has
	// occurred. The map key is the protocol name negotiated (eg
	// websocket, h2c)
	HTTPNextProto map[string]func(*Server, ResponseWriter, *Request)

	// 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)

	// ErrorLog specifies an optional logger for errors accepting
	// connections and unexpected behavior from handlers.
	// If nil, logging goes to os.Stderr via the log package's
	// standard logger.
	ErrorLog *log.Logger

	// CloseNotifyCh allow detecting when the server in graceful shutdown state
	CloseNotifyCh chan bool
	// contains filtered or unexported fields

A Server defines parameters for running an HTTP server. The zero value for Server is a valid configuration.

func (*Server) DoKeepAlives

func (s *Server) DoKeepAlives() bool

func (*Server) SetKeepAlivesEnabled

func (s *Server) SetKeepAlivesEnabled(v bool)

SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. By default, keep-alives are always enabled. Only very resource-constrained environments or servers in the process of shutting down should disable them.

type SignCalculater

type SignCalculater interface {
	CalcSign(feature string) string

The SignCalculater interface is used to calculate signature for response

type Transport

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.
	// If Proxy is nil or returns a nil *URL, no proxy is used.
	Proxy func(*Request) (*url.URL, error)

	// Dial specifies the dial function for creating TCP
	// connections.
	// If Dial is nil, net.Dial is used.
	Dial func(network, addr string) (net.Conn, error)

	// TLSClientConfig specifies the TLS configuration to use with
	// tls.Client. If nil, the default configuration is used.
	TLSClientConfig *bfe_tls.Config

	// DisableKeepAlives, if true, prevents re-use of TCP connections
	// between different HTTP requests.
	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

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

	// MaxConnsPerHost, if non-zero, controls the maximum currency conns
	//  to per-host.  If less than or equal zero, transport will ignore this value.
	MaxConnsPerHost int

	// 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

	// ReqWriteBufferSize specifies writer buffer size for request.
	// If zero, default buffer size is used.
	ReqWriteBufferSize int

	// FlushInterval specifies the flush interval to flush to
	// the backend while copying the request body.
	// If zero, no periodic flushing is done.
	ReqFlushInterval time.Duration
	// contains filtered or unexported fields

Transport is an implementation of RoundTripper that supports http, https, and http proxies (for either http or https with CONNECT). Transport can also cache connections for future re-use.

func (*Transport) CancelRequest

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

CancelRequest cancels an in-flight request by closing its connection.

func (*Transport) CloseIdleConnections

func (t *Transport) CloseIdleConnections()

CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.

func (*Transport) RegisterProtocol

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

RegisterProtocol registers a new protocol with scheme. The Transport will pass requests using the given scheme to rt. It is rt's responsibility to simulate HTTP request semantics.

RegisterProtocol can be used by other packages to provide implementations of protocol schemes like "ftp" or "file".

func (*Transport) RoundTrip

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

RoundTrip implements the RoundTripper interface.

For higher-level HTTP client support (such as handling of cookies and redirects), see Get, Post, and the Client type.

type TransportBrokenError

type TransportBrokenError struct{}

func (TransportBrokenError) Error

func (e TransportBrokenError) Error() string

type WriteFlusher

type WriteFlusher interface {

type WriteRequestError

type WriteRequestError struct {
	Err error

func (WriteRequestError) CheckTargetError

func (e WriteRequestError) CheckTargetError(addr net.Addr) bool

func (WriteRequestError) Error

func (e WriteRequestError) Error() string


Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto