fasthttp: github.com/valyala/fasthttp Index | Examples | Files | Directories

package fasthttp

import "github.com/valyala/fasthttp"

Package fasthttp provides fast HTTP server and client API.

Fasthttp provides the following features:

* Optimized for speed. Easily handles more than 100K qps and more than 1M
  concurrent keep-alive connections on modern hardware.
* Optimized for low memory usage.
* Easy 'Connection: Upgrade' support via RequestCtx.Hijack.
* Server supports requests' pipelining. Multiple requests may be read from
  a single network packet and multiple responses may be sent in a single
  network packet. This may be useful for highly loaded REST services.
* Server provides the following anti-DoS limits:

    * The number of concurrent connections.
    * The number of concurrent connections per client IP.
    * The number of requests per connection.
    * Request read timeout.
    * Response write timeout.
    * Maximum request header size.
    * Maximum request body size.
    * Maximum request execution time.
    * Maximum keep-alive connection lifetime.
    * Early filtering out non-GET requests.

* A lot of additional useful info is exposed to request handler:

    * Server and client address.
    * Per-request logger.
    * Unique request id.
    * Request start time.
    * Connection start time.
    * Request sequence number for the current connection.

* Client supports automatic retry on idempotent requests' failure.
* Fasthttp API is designed with the ability to extend existing client
  and server implementations or to write custom client and server
  implementations from scratch.

Index

Examples

Package Files

args.go bytebuffer.go bytesconv.go bytesconv_64.go client.go coarseTime.go compress.go cookie.go doc.go fs.go header.go http.go lbclient.go nocopy.go peripconn.go server.go status.go stream.go strings.go tcpdialer.go timer.go uri.go uri_unix.go userdata.go workerpool.go

Constants

const (
    CompressNoCompression      = flate.NoCompression
    CompressBestSpeed          = flate.BestSpeed
    CompressBestCompression    = flate.BestCompression
    CompressDefaultCompression = flate.DefaultCompression
)

Supported compression levels.

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

    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
    StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
    StatusLocked                       = 423 // RFC 4918, 11.3
    StatusFailedDependency             = 424 // RFC 4918, 11.4
    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
)

HTTP status codes were stolen from net/http.

const DefaultConcurrency = 256 * 1024

DefaultConcurrency is the maximum number of concurrent connections the Server may serve by default (i.e. if Server.Concurrency isn't set).

const DefaultDNSCacheDuration = time.Minute

DefaultDNSCacheDuration is the duration for caching resolved TCP addresses by Dial* functions.

const DefaultDialTimeout = 3 * time.Second

DefaultDialTimeout is timeout used by Dial and DialDualStack for establishing TCP connections.

const DefaultLBClientTimeout = time.Second

DefaultLBClientTimeout is the default request timeout used by LBClient when calling LBClient.Do.

The timeout may be overriden via LBClient.Timeout.

const DefaultMaxConnsPerHost = 512

DefaultMaxConnsPerHost is the maximum number of concurrent connections http client may establish per host by default (i.e. if Client.MaxConnsPerHost isn't set).

const DefaultMaxIdleConnDuration = 10 * time.Second

DefaultMaxIdleConnDuration is the default duration before idle keep-alive connection is closed.

const DefaultMaxPendingRequests = 1024

DefaultMaxPendingRequests is the default value for PipelineClient.MaxPendingRequests.

const DefaultMaxRequestBodySize = 4 * 1024 * 1024

DefaultMaxRequestBodySize is the maximum request body size the server reads by default.

See Server.MaxRequestBodySize for details.

const FSCompressedFileSuffix = ".fasthttp.gz"

FSCompressedFileSuffix is the suffix FS adds to the original file names when trying to store compressed file under the new file name. See FS.Compress for details.

const FSHandlerCacheDuration = 10 * time.Second

FSHandlerCacheDuration is the default expiration duration for inactive file handlers opened by FS.

Variables

var (
    // ErrNoFreeConns is returned when no free connections available
    // to the given host.
    //
    // Increase the allowed number of connections per host if you
    // see this error.
    ErrNoFreeConns = errors.New("no free connections available to host")

    // ErrTimeout is returned from timed out calls.
    ErrTimeout = errors.New("timeout")

    // ErrConnectionClosed may be returned from client methods if the server
    // closes connection before returning the first response byte.
    //
    // If you see this error, then either fix the server by returning
    // 'Connection: close' response header before closing the connection
    // or add 'Connection: close' request header before sending requests
    // to broken server.
    ErrConnectionClosed = errors.New("the server closed connection before returning the first response byte. " +
        "Make sure the server returns 'Connection: close' response header before closing the connection")
)
var (
    // CookieExpireDelete may be set on Cookie.Expire for expiring the given cookie.
    CookieExpireDelete = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)

    // CookieExpireUnlimited indicates that the cookie doesn't expire.
    CookieExpireUnlimited = zeroTime
)
var (
    // ErrPerIPConnLimit may be returned from ServeConn if the number of connections
    // per ip exceeds Server.MaxConnsPerIP.
    ErrPerIPConnLimit = errors.New("too many connections per ip")

    // ErrConcurrencyLimit may be returned from ServeConn if the number
    // of concurrenty served connections exceeds Server.Concurrency.
    ErrConcurrencyLimit = errors.New("canot serve the connection because Server.Concurrency concurrent connections are served")

    // ErrKeepaliveTimeout is returned from ServeConn
    // if the connection lifetime exceeds MaxKeepaliveDuration.
    ErrKeepaliveTimeout = errors.New("exceeded MaxKeepaliveDuration")
)
var ErrBodyTooLarge = errors.New("body size exceeds the given limit")

ErrBodyTooLarge is returned if either request or response body exceeds the given limit.

var ErrDialTimeout = errors.New("dialing to the given TCP address timed out")

ErrDialTimeout is returned when TCP dialing is timed out.

var ErrMissingFile = errors.New("there is no uploaded file associated with the given key")

ErrMissingFile may be returned from FormFile when the is no uploaded file associated with the given multipart form key.

var ErrNoArgValue = errors.New("no Args value for the given key")

ErrNoArgValue is returned when Args value with the given key is missing.

var ErrNoMultipartForm = errors.New("request has no multipart/form-data Content-Type")

ErrNoMultipartForm means that the request's Content-Type isn't 'multipart/form-data'.

var ErrPipelineOverflow = errors.New("pipelined requests' queue has been overflown. Increase MaxConns and/or MaxPendingRequests")

ErrPipelineOverflow may be returned from PipelineClient.Do* if the requests' queue is overflown.

func AppendBytesStr Uses

func AppendBytesStr(dst []byte, src string) []byte

AppendBytesStr appends src to dst and returns the extended dst.

This function has no performance benefits comparing to append(dst, src...). It is left here for backwards compatibility only.

This function is deprecated and may be deleted soon.

func AppendGunzipBytes Uses

func AppendGunzipBytes(dst, src []byte) ([]byte, error)

AppendGunzipBytes append gunzipped src to dst and returns the resulting dst.

func AppendGzipBytes Uses

func AppendGzipBytes(dst, src []byte) []byte

AppendGzipBytes appends gzipped src to dst and returns the resulting dst.

func AppendGzipBytesLevel Uses

func AppendGzipBytesLevel(dst, src []byte, level int) []byte

AppendGzipBytesLevel appends gzipped src to dst using the given compression level and returns the resulting dst.

Supported compression levels are:

* CompressNoCompression
* CompressBestSpeed
* CompressBestCompression
* CompressDefaultCompression

func AppendHTMLEscape Uses

func AppendHTMLEscape(dst []byte, s string) []byte

AppendHTMLEscape appends html-escaped s to dst and returns the extended dst.

func AppendHTMLEscapeBytes Uses

func AppendHTMLEscapeBytes(dst, s []byte) []byte

AppendHTMLEscapeBytes appends html-escaped s to dst and returns the extended dst.

func AppendHTTPDate Uses

func AppendHTTPDate(dst []byte, date time.Time) []byte

AppendHTTPDate appends HTTP-compliant (RFC1123) representation of date to dst and returns the extended dst.

func AppendIPv4 Uses

func AppendIPv4(dst []byte, ip net.IP) []byte

AppendIPv4 appends string representation of the given ip v4 to dst and returns the extended dst.

func AppendNormalizedHeaderKey Uses

func AppendNormalizedHeaderKey(dst []byte, key string) []byte

AppendNormalizedHeaderKey appends normalized header key (name) to dst and returns the resulting dst.

Normalized header key starts with uppercase letter. The first letters after dashes are also uppercased. All the other letters are lowercased. Examples:

* coNTENT-TYPe -> Content-Type
* HOST -> Host
* foo-bar-baz -> Foo-Bar-Baz

func AppendNormalizedHeaderKeyBytes Uses

func AppendNormalizedHeaderKeyBytes(dst, key []byte) []byte

AppendNormalizedHeaderKeyBytes appends normalized header key (name) to dst and returns the resulting dst.

Normalized header key starts with uppercase letter. The first letters after dashes are also uppercased. All the other letters are lowercased. Examples:

* coNTENT-TYPe -> Content-Type
* HOST -> Host
* foo-bar-baz -> Foo-Bar-Baz

func AppendQuotedArg Uses

func AppendQuotedArg(dst, src []byte) []byte

AppendQuotedArg appends url-encoded src to dst and returns appended dst.

func AppendUint Uses

func AppendUint(dst []byte, n int) []byte

AppendUint appends n to dst and returns the extended dst.

func CoarseTimeNow Uses

func CoarseTimeNow() time.Time

CoarseTimeNow returns the current time truncated to the nearest second.

This is a faster alternative to time.Now().

func Dial Uses

func Dial(addr string) (net.Conn, error)

Dial dials the given TCP addr using tcp4.

This function has the following additional features comparing to net.Dial:

* It reduces load on DNS resolver by caching resolved TCP addressed
  for DefaultDNSCacheDuration.
* It dials all the resolved TCP addresses in round-robin manner until
  connection is established. This may be useful if certain addresses
  are temporarily unreachable.
* It returns ErrDialTimeout if connection cannot be established during
  DefaultDialTimeout seconds. Use DialTimeout for customizing dial timeout.

This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial.

For instance, per-host counters and/or limits may be implemented by such wrappers.

The addr passed to the function must contain port. Example addr values:

* foobar.baz:443
* foo.bar:80
* aaa.com:8080

func DialDualStack Uses

func DialDualStack(addr string) (net.Conn, error)

DialDualStack dials the given TCP addr using both tcp4 and tcp6.

This function has the following additional features comparing to net.Dial:

* It reduces load on DNS resolver by caching resolved TCP addressed
  for DefaultDNSCacheDuration.
* It dials all the resolved TCP addresses in round-robin manner until
  connection is established. This may be useful if certain addresses
  are temporarily unreachable.
* It returns ErrDialTimeout if connection cannot be established during
  DefaultDialTimeout seconds. Use DialDualStackTimeout for custom dial
  timeout.

This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial.

For instance, per-host counters and/or limits may be implemented by such wrappers.

The addr passed to the function must contain port. Example addr values:

* foobar.baz:443
* foo.bar:80
* aaa.com:8080

func DialDualStackTimeout Uses

func DialDualStackTimeout(addr string, timeout time.Duration) (net.Conn, error)

DialDualStackTimeout dials the given TCP addr using both tcp4 and tcp6 using the given timeout.

This function has the following additional features comparing to net.Dial:

* It reduces load on DNS resolver by caching resolved TCP addressed
  for DefaultDNSCacheDuration.
* It dials all the resolved TCP addresses in round-robin manner until
  connection is established. This may be useful if certain addresses
  are temporarily unreachable.

This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial.

For instance, per-host counters and/or limits may be implemented by such wrappers.

The addr passed to the function must contain port. Example addr values:

* foobar.baz:443
* foo.bar:80
* aaa.com:8080

func DialTimeout Uses

func DialTimeout(addr string, timeout time.Duration) (net.Conn, error)

DialTimeout dials the given TCP addr using tcp4 using the given timeout.

This function has the following additional features comparing to net.Dial:

* It reduces load on DNS resolver by caching resolved TCP addressed
  for DefaultDNSCacheDuration.
* It dials all the resolved TCP addresses in round-robin manner until
  connection is established. This may be useful if certain addresses
  are temporarily unreachable.

This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial.

For instance, per-host counters and/or limits may be implemented by such wrappers.

The addr passed to the function must contain port. Example addr values:

* foobar.baz:443
* foo.bar:80
* aaa.com:8080

func Do Uses

func Do(req *Request, resp *Response) error

Do performs the given http request and fills the given http response.

Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.

Client determines the server to be requested in the following order:

- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.

The function doesn't follow redirects. Use Get* for following redirects.

Response is ignored if resp is nil.

ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy.

It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.

func DoDeadline Uses

func DoDeadline(req *Request, resp *Response, deadline time.Time) error

DoDeadline performs the given request and waits for response until the given deadline.

Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.

Client determines the server to be requested in the following order:

- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.

The function doesn't follow redirects. Use Get* for following redirects.

Response is ignored if resp is nil.

ErrTimeout is returned if the response wasn't returned until the given deadline.

ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy.

It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.

func DoTimeout Uses

func DoTimeout(req *Request, resp *Response, timeout time.Duration) error

DoTimeout performs the given request and waits for response during the given timeout duration.

Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.

Client determines the server to be requested in the following order:

- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.

The function doesn't follow redirects. Use Get* for following redirects.

Response is ignored if resp is nil.

ErrTimeout is returned if the response wasn't returned during the given timeout.

ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy.

It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.

func EqualBytesStr Uses

func EqualBytesStr(b []byte, s string) bool

EqualBytesStr returns true if string(b) == s.

This function has no performance benefits comparing to string(b) == s. It is left here for backwards compatibility only.

This function is deperecated and may be deleted soon.

func FileLastModified Uses

func FileLastModified(path string) (time.Time, error)

FileLastModified returns last modified time for the file.

func Get Uses

func Get(dst []byte, url string) (statusCode int, body []byte, err error)

Get appends url contents to dst and returns it as body.

The function follows redirects. Use Do* for manually handling redirects.

New body buffer is allocated if dst is nil.

func GetDeadline Uses

func GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error)

GetDeadline appends url contents to dst and returns it as body.

The function follows redirects. Use Do* for manually handling redirects.

New body buffer is allocated if dst is nil.

ErrTimeout error is returned if url contents couldn't be fetched until the given deadline.

func GetTimeout Uses

func GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error)

GetTimeout appends url contents to dst and returns it as body.

The function follows redirects. Use Do* for manually handling redirects.

New body buffer is allocated if dst is nil.

ErrTimeout error is returned if url contents couldn't be fetched during the given timeout.

func ListenAndServe Uses

func ListenAndServe(addr string, handler RequestHandler) error

ListenAndServe serves HTTP requests from the given TCP addr using the given handler.

Code:

// The server will listen for incoming requests on this address.
listenAddr := "127.0.0.1:80"

// This function will be called by the server for each incoming request.
//
// RequestCtx provides a lot of functionality related to http request
// processing. See RequestCtx docs for details.
requestHandler := func(ctx *fasthttp.RequestCtx) {
    fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path())
}

// Start the server with default settings.
// Create Server instance for adjusting server settings.
//
// ListenAndServe returns only on error, so usually it blocks forever.
if err := fasthttp.ListenAndServe(listenAddr, requestHandler); err != nil {
    log.Fatalf("error in ListenAndServe: %s", err)
}

func ListenAndServeTLS Uses

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

ListenAndServeTLS serves HTTPS requests from the given TCP addr using the given handler.

certFile and keyFile are paths to TLS certificate and key files.

func ListenAndServeTLSEmbed Uses

func ListenAndServeTLSEmbed(addr string, certData, keyData []byte, handler RequestHandler) error

ListenAndServeTLSEmbed serves HTTPS requests from the given TCP addr using the given handler.

certData and keyData must contain valid TLS certificate and key data.

func ListenAndServeUNIX Uses

func ListenAndServeUNIX(addr string, mode os.FileMode, handler RequestHandler) error

ListenAndServeUNIX serves HTTP requests from the given UNIX addr using the given handler.

The function deletes existing file at addr before starting serving.

The server sets the given file mode for the UNIX addr.

func NewStreamReader Uses

func NewStreamReader(sw StreamWriter) io.ReadCloser

NewStreamReader returns a reader, which replays all the data generated by sw.

The returned reader may be passed to Response.SetBodyStream.

Close must be called on the returned reader after all the required data has been read. Otherwise goroutine leak may occur.

See also Response.SetBodyStreamWriter.

func ParseByteRange Uses

func ParseByteRange(byteRange []byte, contentLength int) (startPos, endPos int, err error)

ParseByteRange parses 'Range: bytes=...' header value.

It follows https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 .

func ParseHTTPDate Uses

func ParseHTTPDate(date []byte) (time.Time, error)

ParseHTTPDate parses HTTP-compliant (RFC1123) date.

func ParseIPv4 Uses

func ParseIPv4(dst net.IP, ipStr []byte) (net.IP, error)

ParseIPv4 parses ip address from ipStr into dst and returns the extended dst.

func ParseUfloat Uses

func ParseUfloat(buf []byte) (float64, error)

ParseUfloat parses unsigned float from buf.

func ParseUint Uses

func ParseUint(buf []byte) (int, error)

ParseUint parses uint from buf.

func Post Uses

func Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error)

Post sends POST request to the given url with the given POST arguments.

Response body is appended to dst, which is returned as body.

The function follows redirects. Use Do* for manually handling redirects.

New body buffer is allocated if dst is nil.

Empty POST body is sent if postArgs is nil.

func ReleaseArgs Uses

func ReleaseArgs(a *Args)

ReleaseArgs returns the object acquired via AquireArgs to the pool.

Do not access the released Args object, otherwise data races may occur.

func ReleaseByteBuffer Uses

func ReleaseByteBuffer(b *ByteBuffer)

ReleaseByteBuffer returns byte buffer to the pool.

ByteBuffer.B mustn't be touched after returning it to the pool. Otherwise data races occur.

func ReleaseCookie Uses

func ReleaseCookie(c *Cookie)

ReleaseCookie returns the Cookie object acquired with AcquireCookie back to the pool.

Do not access released Cookie object, otherwise data races may occur.

func ReleaseRequest Uses

func ReleaseRequest(req *Request)

ReleaseRequest returns req acquired via AcquireRequest to request pool.

It is forbidden accessing req and/or its' members after returning it to request pool.

func ReleaseResponse Uses

func ReleaseResponse(resp *Response)

ReleaseResponse return resp acquired via AcquireResponse to response pool.

It is forbidden accessing resp and/or its' members after returning it to response pool.

func ReleaseURI Uses

func ReleaseURI(u *URI)

ReleaseURI releases the URI acquired via AcquireURI.

The released URI mustn't be used after releasing it, otherwise data races may occur.

func SaveMultipartFile Uses

func SaveMultipartFile(fh *multipart.FileHeader, path string) error

SaveMultipartFile saves multipart file fh under the given filename path.

func Serve Uses

func Serve(ln net.Listener, handler RequestHandler) error

Serve serves incoming connections from the given listener using the given handler.

Serve blocks until the given listener returns permanent error.

Code:

// Create network listener for accepting incoming requests.
//
// Note that you are not limited by TCP listener - arbitrary
// net.Listener may be used by the server.
// For example, unix socket listener or TLS listener.
ln, err := net.Listen("tcp4", "127.0.0.1:8080")
if err != nil {
    log.Fatalf("error in net.Listen: %s", err)
}

// This function will be called by the server for each incoming request.
//
// RequestCtx provides a lot of functionality related to http request
// processing. See RequestCtx docs for details.
requestHandler := func(ctx *fasthttp.RequestCtx) {
    fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path())
}

// Start the server with default settings.
// Create Server instance for adjusting server settings.
//
// Serve returns on ln.Close() or error, so usually it blocks forever.
if err := fasthttp.Serve(ln, requestHandler); err != nil {
    log.Fatalf("error in Serve: %s", err)
}

func ServeConn Uses

func ServeConn(c net.Conn, handler RequestHandler) error

ServeConn serves HTTP requests from the given connection using the given handler.

ServeConn returns nil if all requests from the c are successfully served. It returns non-nil error otherwise.

Connection c must immediately propagate all the data passed to Write() to the client. Otherwise requests' processing may hang.

ServeConn closes c before returning.

func ServeFile Uses

func ServeFile(ctx *RequestCtx, path string)

ServeFile returns HTTP response containing compressed file contents from the given path.

HTTP response may contain uncompressed file contents in the following cases:

* Missing 'Accept-Encoding: gzip' request header.
* No write access to directory containing the file.

Directory contents is returned if path points to directory.

Use ServeFileUncompressed is you don't need serving compressed file contents.

See also RequestCtx.SendFile.

func ServeFileBytes Uses

func ServeFileBytes(ctx *RequestCtx, path []byte)

ServeFileBytes returns HTTP response containing compressed file contents from the given path.

HTTP response may contain uncompressed file contents in the following cases:

* Missing 'Accept-Encoding: gzip' request header.
* No write access to directory containing the file.

Directory contents is returned if path points to directory.

Use ServeFileBytesUncompressed is you don't need serving compressed file contents.

See also RequestCtx.SendFileBytes.

func ServeFileBytesUncompressed Uses

func ServeFileBytesUncompressed(ctx *RequestCtx, path []byte)

ServeFileBytesUncompressed returns HTTP response containing file contents from the given path.

Directory contents is returned if path points to directory.

ServeFileBytes may be used for saving network traffic when serving files with good compression ratio.

See also RequestCtx.SendFileBytes.

func ServeFileUncompressed Uses

func ServeFileUncompressed(ctx *RequestCtx, path string)

ServeFileUncompressed returns HTTP response containing file contents from the given path.

Directory contents is returned if path points to directory.

ServeFile may be used for saving network traffic when serving files with good compression ratio.

See also RequestCtx.SendFile.

func ServeTLS Uses

func ServeTLS(ln net.Listener, certFile, keyFile string, handler RequestHandler) error

ServeTLS serves HTTPS requests from the given net.Listener using the given handler.

certFile and keyFile are paths to TLS certificate and key files.

func ServeTLSEmbed Uses

func ServeTLSEmbed(ln net.Listener, certData, keyData []byte, handler RequestHandler) error

ServeTLSEmbed serves HTTPS requests from the given net.Listener using the given handler.

certData and keyData must contain valid TLS certificate and key data.

func StatusMessage Uses

func StatusMessage(statusCode int) string

StatusMessage returns HTTP status message for the given status code.

func WriteGunzip Uses

func WriteGunzip(w io.Writer, p []byte) (int, error)

WriteGunzip writes ungzipped p to w and returns the number of uncompressed bytes written to w.

func WriteGzip Uses

func WriteGzip(w io.Writer, p []byte) (int, error)

WriteGzip writes gzipped p to w and returns the number of compressed bytes written to w.

func WriteGzipLevel Uses

func WriteGzipLevel(w io.Writer, p []byte, level int) (int, error)

WriteGzipLevel writes gzipped p to w using the given compression level and returns the number of compressed bytes written to w.

Supported compression levels are:

* CompressNoCompression
* CompressBestSpeed
* CompressBestCompression
* CompressDefaultCompression

func WriteInflate Uses

func WriteInflate(w io.Writer, p []byte) (int, error)

WriteInflate writes inflated p to w and returns the number of uncompressed bytes written to w.

func WriteMultipartForm Uses

func WriteMultipartForm(w io.Writer, f *multipart.Form, boundary string) error

WriteMultipartForm writes the given multipart form f with the given boundary to w.

type Args Uses

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

Args represents query arguments.

It is forbidden copying Args instances. Create new instances instead and use CopyTo().

Args instance MUST NOT be used from concurrently running goroutines.

func AcquireArgs Uses

func AcquireArgs() *Args

AcquireArgs returns an empty Args object from the pool.

The returned Args may be returned to the pool with ReleaseArgs when no longer needed. This allows reducing GC load.

func (*Args) Add Uses

func (a *Args) Add(key, value string)

Add adds 'key=value' argument.

Multiple values for the same key may be added.

func (*Args) AddBytesK Uses

func (a *Args) AddBytesK(key []byte, value string)

AddBytesK adds 'key=value' argument.

Multiple values for the same key may be added.

func (*Args) AddBytesKV Uses

func (a *Args) AddBytesKV(key, value []byte)

AddBytesKV adds 'key=value' argument.

Multiple values for the same key may be added.

func (*Args) AddBytesV Uses

func (a *Args) AddBytesV(key string, value []byte)

AddBytesV adds 'key=value' argument.

Multiple values for the same key may be added.

func (*Args) AppendBytes Uses

func (a *Args) AppendBytes(dst []byte) []byte

AppendBytes appends query string to dst and returns the extended dst.

func (*Args) CopyTo Uses

func (a *Args) CopyTo(dst *Args)

CopyTo copies all args to dst.

func (*Args) Del Uses

func (a *Args) Del(key string)

Del deletes argument with the given key from query args.

func (*Args) DelBytes Uses

func (a *Args) DelBytes(key []byte)

DelBytes deletes argument with the given key from query args.

func (*Args) GetBool Uses

func (a *Args) GetBool(key string) bool

GetBool returns boolean value for the given key.

true is returned for '1', 'y' and 'yes' values, otherwise false is returned.

func (*Args) GetUfloat Uses

func (a *Args) GetUfloat(key string) (float64, error)

GetUfloat returns ufloat value for the given key.

func (*Args) GetUfloatOrZero Uses

func (a *Args) GetUfloatOrZero(key string) float64

GetUfloatOrZero returns ufloat value for the given key.

Zero (0) is returned on error.

func (*Args) GetUint Uses

func (a *Args) GetUint(key string) (int, error)

GetUint returns uint value for the given key.

func (*Args) GetUintOrZero Uses

func (a *Args) GetUintOrZero(key string) int

GetUintOrZero returns uint value for the given key.

Zero (0) is returned on error.

func (*Args) Has Uses

func (a *Args) Has(key string) bool

Has returns true if the given key exists in Args.

func (*Args) HasBytes Uses

func (a *Args) HasBytes(key []byte) bool

HasBytes returns true if the given key exists in Args.

func (*Args) Len Uses

func (a *Args) Len() int

Len returns the number of query args.

func (*Args) Parse Uses

func (a *Args) Parse(s string)

Parse parses the given string containing query args.

func (*Args) ParseBytes Uses

func (a *Args) ParseBytes(b []byte)

ParseBytes parses the given b containing query args.

func (*Args) Peek Uses

func (a *Args) Peek(key string) []byte

Peek returns query arg value for the given key.

Returned value is valid until the next Args call.

func (*Args) PeekBytes Uses

func (a *Args) PeekBytes(key []byte) []byte

PeekBytes returns query arg value for the given key.

Returned value is valid until the next Args call.

func (*Args) PeekMulti Uses

func (a *Args) PeekMulti(key string) [][]byte

PeekMulti returns all the arg values for the given key.

func (*Args) PeekMultiBytes Uses

func (a *Args) PeekMultiBytes(key []byte) [][]byte

PeekMultiBytes returns all the arg values for the given key.

func (*Args) QueryString Uses

func (a *Args) QueryString() []byte

QueryString returns query string for the args.

The returned value is valid until the next call to Args methods.

func (*Args) Reset Uses

func (a *Args) Reset()

Reset clears query args.

func (*Args) Set Uses

func (a *Args) Set(key, value string)

Set sets 'key=value' argument.

func (*Args) SetBytesK Uses

func (a *Args) SetBytesK(key []byte, value string)

SetBytesK sets 'key=value' argument.

func (*Args) SetBytesKV Uses

func (a *Args) SetBytesKV(key, value []byte)

SetBytesKV sets 'key=value' argument.

func (*Args) SetBytesV Uses

func (a *Args) SetBytesV(key string, value []byte)

SetBytesV sets 'key=value' argument.

func (*Args) SetUint Uses

func (a *Args) SetUint(key string, value int)

SetUint sets uint value for the given key.

func (*Args) SetUintBytes Uses

func (a *Args) SetUintBytes(key []byte, value int)

SetUintBytes sets uint value for the given key.

func (*Args) String Uses

func (a *Args) String() string

String returns string representation of query args.

func (*Args) VisitAll Uses

func (a *Args) VisitAll(f func(key, value []byte))

VisitAll calls f for each existing arg.

f must not retain references to key and value after returning. Make key and/or value copies if you need storing them after returning.

func (*Args) WriteTo Uses

func (a *Args) WriteTo(w io.Writer) (int64, error)

WriteTo writes query string to w.

WriteTo implements io.WriterTo interface.

type BalancingClient Uses

type BalancingClient interface {
    DoDeadline(req *Request, resp *Response, deadline time.Time) error
    PendingRequests() int
}

BalancingClient is the interface for clients, which may be passed to LBClient.Clients.

type ByteBuffer Uses

type ByteBuffer bytebufferpool.ByteBuffer

ByteBuffer provides byte buffer, which can be used with fasthttp API in order to minimize memory allocations.

ByteBuffer may be used with functions appending data to the given []byte slice. See example code for details.

Use AcquireByteBuffer for obtaining an empty byte buffer.

ByteBuffer is deprecated. Use github.com/valyala/bytebufferpool instead.

Code:

// This request handler sets 'Your-IP' response header
// to 'Your IP is <ip>'. It uses ByteBuffer for constructing response
// header value with zero memory allocations.
yourIPRequestHandler := func(ctx *fasthttp.RequestCtx) {
    b := fasthttp.AcquireByteBuffer()
    b.B = append(b.B, "Your IP is <"...)
    b.B = fasthttp.AppendIPv4(b.B, ctx.RemoteIP())
    b.B = append(b.B, ">"...)
    ctx.Response.Header.SetBytesV("Your-IP", b.B)

    fmt.Fprintf(ctx, "Check response headers - they must contain 'Your-IP: %s'", b.B)

    // It is safe to release byte buffer now, since it is
    // no longer used.
    fasthttp.ReleaseByteBuffer(b)
}

// Start fasthttp server returning your ip in response headers.
fasthttp.ListenAndServe(":8080", yourIPRequestHandler)

func AcquireByteBuffer Uses

func AcquireByteBuffer() *ByteBuffer

AcquireByteBuffer returns an empty byte buffer from the pool.

Acquired byte buffer may be returned to the pool via ReleaseByteBuffer call. This reduces the number of memory allocations required for byte buffer management.

func (*ByteBuffer) Reset Uses

func (b *ByteBuffer) Reset()

Reset makes ByteBuffer.B empty.

func (*ByteBuffer) Set Uses

func (b *ByteBuffer) Set(p []byte)

Set sets ByteBuffer.B to p

func (*ByteBuffer) SetString Uses

func (b *ByteBuffer) SetString(s string)

SetString sets ByteBuffer.B to s

func (*ByteBuffer) Write Uses

func (b *ByteBuffer) Write(p []byte) (int, error)

Write implements io.Writer - it appends p to ByteBuffer.B

func (*ByteBuffer) WriteString Uses

func (b *ByteBuffer) WriteString(s string) (int, error)

WriteString appends s to ByteBuffer.B

type Client Uses

type Client struct {

    // Client name. Used in User-Agent request header.
    //
    // Default client name is used if not set.
    Name string

    // Callback for establishing new connections to hosts.
    //
    // Default Dial is used if not set.
    Dial DialFunc

    // Attempt to connect to both ipv4 and ipv6 addresses if set to true.
    //
    // This option is used only if default TCP dialer is used,
    // i.e. if Dial is blank.
    //
    // By default client connects only to ipv4 addresses,
    // since unfortunately ipv6 remains broken in many networks worldwide :)
    DialDualStack bool

    // TLS config for https connections.
    //
    // Default TLS config is used if not set.
    TLSConfig *tls.Config

    // Maximum number of connections per each host which may be established.
    //
    // DefaultMaxConnsPerHost is used if not set.
    MaxConnsPerHost int

    // Idle keep-alive connections are closed after this duration.
    //
    // By default idle connections are closed
    // after DefaultMaxIdleConnDuration.
    MaxIdleConnDuration time.Duration

    // Per-connection buffer size for responses' reading.
    // This also limits the maximum header size.
    //
    // Default buffer size is used if 0.
    ReadBufferSize int

    // Per-connection buffer size for requests' writing.
    //
    // Default buffer size is used if 0.
    WriteBufferSize int

    // Maximum duration for full response reading (including body).
    //
    // By default response read timeout is unlimited.
    ReadTimeout time.Duration

    // Maximum duration for full request writing (including body).
    //
    // By default request write timeout is unlimited.
    WriteTimeout time.Duration

    // Maximum response body size.
    //
    // The client returns ErrBodyTooLarge if this limit is greater than 0
    // and response body is greater than the limit.
    //
    // By default response body size is unlimited.
    MaxResponseBodySize int

    // Header names are passed as-is without normalization
    // if this option is set.
    //
    // Disabled header names' normalization may be useful only for proxying
    // responses to other clients expecting case-sensitive
    // header names. See https://github.com/valyala/fasthttp/issues/57
    // for details.
    //
    // By default request and response header names are normalized, i.e.
    // The first letter and the first letters following dashes
    // are uppercased, while all the other letters are lowercased.
    // Examples:
    //
    //     * HOST -> Host
    //     * content-type -> Content-Type
    //     * cONTENT-lenGTH -> Content-Length
    DisableHeaderNamesNormalizing bool
    // contains filtered or unexported fields
}

Client implements http client.

Copying Client by value is prohibited. Create new instance instead.

It is safe calling Client methods from concurrently running goroutines.

func (*Client) Do Uses

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

Do performs the given http request and fills the given http response.

Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.

Client determines the server to be requested in the following order:

- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.

Response is ignored if resp is nil.

The function doesn't follow redirects. Use Get* for following redirects.

ErrNoFreeConns is returned if all Client.MaxConnsPerHost connections to the requested host are busy.

It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.

func (*Client) DoDeadline Uses

func (c *Client) DoDeadline(req *Request, resp *Response, deadline time.Time) error

DoDeadline performs the given request and waits for response until the given deadline.

Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.

Client determines the server to be requested in the following order:

- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.

The function doesn't follow redirects. Use Get* for following redirects.

Response is ignored if resp is nil.

ErrTimeout is returned if the response wasn't returned until the given deadline.

ErrNoFreeConns is returned if all Client.MaxConnsPerHost connections to the requested host are busy.

/ It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.

func (*Client) DoTimeout Uses

func (c *Client) DoTimeout(req *Request, resp *Response, timeout time.Duration) error

DoTimeout performs the given request and waits for response during the given timeout duration.

Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.

Client determines the server to be requested in the following order:

- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.

The function doesn't follow redirects. Use Get* for following redirects.

Response is ignored if resp is nil.

ErrTimeout is returned if the response wasn't returned during the given timeout.

ErrNoFreeConns is returned if all Client.MaxConnsPerHost connections to the requested host are busy.

It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.

func (*Client) Get Uses

func (c *Client) Get(dst []byte, url string) (statusCode int, body []byte, err error)

Get appends url contents to dst and returns it as body.

The function follows redirects. Use Do* for manually handling redirects.

New body buffer is allocated if dst is nil.

func (*Client) GetDeadline Uses

func (c *Client) GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error)

GetDeadline appends url contents to dst and returns it as body.

The function follows redirects. Use Do* for manually handling redirects.

New body buffer is allocated if dst is nil.

ErrTimeout error is returned if url contents couldn't be fetched until the given deadline.

func (*Client) GetTimeout Uses

func (c *Client) GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error)

GetTimeout appends url contents to dst and returns it as body.

The function follows redirects. Use Do* for manually handling redirects.

New body buffer is allocated if dst is nil.

ErrTimeout error is returned if url contents couldn't be fetched during the given timeout.

func (*Client) Post Uses

func (c *Client) Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error)

Post sends POST request to the given url with the given POST arguments.

Response body is appended to dst, which is returned as body.

The function follows redirects. Use Do* for manually handling redirects.

New body buffer is allocated if dst is nil.

Empty POST body is sent if postArgs is nil.

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

Cookie represents HTTP response cookie.

Do not copy Cookie objects. Create new object and use CopyTo instead.

Cookie instance MUST NOT be used from concurrently running goroutines.

func AcquireCookie Uses

func AcquireCookie() *Cookie

AcquireCookie returns an empty Cookie object from the pool.

The returned object may be returned back to the pool with ReleaseCookie. This allows reducing GC load.

func (*Cookie) AppendBytes Uses

func (c *Cookie) AppendBytes(dst []byte) []byte

AppendBytes appends cookie representation to dst and returns the extended dst.

func (*Cookie) Cookie Uses

func (c *Cookie) Cookie() []byte

Cookie returns cookie representation.

The returned value is valid until the next call to Cookie methods.

func (*Cookie) CopyTo Uses

func (c *Cookie) CopyTo(src *Cookie)

CopyTo copies src cookie to c.

func (*Cookie) Domain Uses

func (c *Cookie) Domain() []byte

Domain returns cookie domain.

The returned domain is valid until the next Cookie modification method call.

func (*Cookie) Expire Uses

func (c *Cookie) Expire() time.Time

Expire returns cookie expiration time.

CookieExpireUnlimited is returned if cookie doesn't expire

func (*Cookie) HTTPOnly Uses

func (c *Cookie) HTTPOnly() bool

HTTPOnly returns true if the cookie is http only.

func (*Cookie) Key Uses

func (c *Cookie) Key() []byte

Key returns cookie name.

The returned value is valid until the next Cookie modification method call.

func (*Cookie) Parse Uses

func (c *Cookie) Parse(src string) error

Parse parses Set-Cookie header.

func (*Cookie) ParseBytes Uses

func (c *Cookie) ParseBytes(src []byte) error

ParseBytes parses Set-Cookie header.

func (*Cookie) Path Uses

func (c *Cookie) Path() []byte

Path returns cookie path.

func (*Cookie) Reset Uses

func (c *Cookie) Reset()

Reset clears the cookie.

func (*Cookie) Secure Uses

func (c *Cookie) Secure() bool

Secure returns true if the cookie is secure.

func (*Cookie) SetDomain Uses

func (c *Cookie) SetDomain(domain string)

SetDomain sets cookie domain.

func (*Cookie) SetDomainBytes Uses

func (c *Cookie) SetDomainBytes(domain []byte)

SetDomainBytes sets cookie domain.

func (*Cookie) SetExpire Uses

func (c *Cookie) SetExpire(expire time.Time)

SetExpire sets cookie expiration time.

Set expiration time to CookieExpireDelete for expiring (deleting) the cookie on the client.

By default cookie lifetime is limited by browser session.

func (*Cookie) SetHTTPOnly Uses

func (c *Cookie) SetHTTPOnly(httpOnly bool)

SetHTTPOnly sets cookie's httpOnly flag to the given value.

func (*Cookie) SetKey Uses

func (c *Cookie) SetKey(key string)

SetKey sets cookie name.

func (*Cookie) SetKeyBytes Uses

func (c *Cookie) SetKeyBytes(key []byte)

SetKeyBytes sets cookie name.

func (*Cookie) SetPath Uses

func (c *Cookie) SetPath(path string)

SetPath sets cookie path.

func (*Cookie) SetPathBytes Uses

func (c *Cookie) SetPathBytes(path []byte)

SetPathBytes sets cookie path.

func (*Cookie) SetSecure Uses

func (c *Cookie) SetSecure(secure bool)

SetSecure sets cookie's secure flag to the given value.

func (*Cookie) SetValue Uses

func (c *Cookie) SetValue(value string)

SetValue sets cookie value.

func (*Cookie) SetValueBytes Uses

func (c *Cookie) SetValueBytes(value []byte)

SetValueBytes sets cookie value.

func (*Cookie) String Uses

func (c *Cookie) String() string

String returns cookie representation.

func (*Cookie) Value Uses

func (c *Cookie) Value() []byte

Value returns cookie value.

The returned value is valid until the next Cookie modification method call.

func (*Cookie) WriteTo Uses

func (c *Cookie) WriteTo(w io.Writer) (int64, error)

WriteTo writes cookie representation to w.

WriteTo implements io.WriterTo interface.

type DialFunc Uses

type DialFunc func(addr string) (net.Conn, error)

DialFunc must establish connection to addr.

There is no need in establishing TLS (SSL) connection for https. The client automatically converts connection to TLS if HostClient.IsTLS is set.

TCP address passed to DialFunc always contains host and port. Example TCP addr values:

- foobar.com:80
- foobar.com:443
- foobar.com:8080

type ErrSmallBuffer Uses

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

ErrSmallBuffer is returned when the provided buffer size is too small for reading request and/or response headers.

ReadBufferSize value from Server or clients should reduce the number of such errors.

type FS Uses

type FS struct {

    // Path to the root directory to serve files from.
    Root string

    // List of index file names to try opening during directory access.
    //
    // For example:
    //
    //     * index.html
    //     * index.htm
    //     * my-super-index.xml
    //
    // By default the list is empty.
    IndexNames []string

    // Index pages for directories without files matching IndexNames
    // are automatically generated if set.
    //
    // Directory index generation may be quite slow for directories
    // with many files (more than 1K), so it is discouraged enabling
    // index pages' generation for such directories.
    //
    // By default index pages aren't generated.
    GenerateIndexPages bool

    // Transparently compresses responses if set to true.
    //
    // The server tries minimizing CPU usage by caching compressed files.
    // It adds CompressedFileSuffix suffix to the original file name and
    // tries saving the resulting compressed file under the new file name.
    // So it is advisable to give the server write access to Root
    // and to all inner folders in order to minimze CPU usage when serving
    // compressed responses.
    //
    // Transparent compression is disabled by default.
    Compress bool

    // Enables byte range requests if set to true.
    //
    // Byte range requests are disabled by default.
    AcceptByteRange bool

    // Path rewriting function.
    //
    // By default request path is not modified.
    PathRewrite PathRewriteFunc

    // Expiration duration for inactive file handlers.
    //
    // FSHandlerCacheDuration is used by default.
    CacheDuration time.Duration

    // Suffix to add to the name of cached compressed file.
    //
    // This value has sense only if Compress is set.
    //
    // FSCompressedFileSuffix is used by default.
    CompressedFileSuffix string
    // contains filtered or unexported fields
}

FS represents settings for request handler serving static files from the local filesystem.

It is prohibited copying FS values. Create new values instead.

Code:

fs := &fasthttp.FS{
    // Path to directory to serve.
    Root: "/var/www/static-site",

    // Generate index pages if client requests directory contents.
    GenerateIndexPages: true,

    // Enable transparent compression to save network traffic.
    Compress: true,
}

// Create request handler for serving static files.
h := fs.NewRequestHandler()

// Start the server.
if err := fasthttp.ListenAndServe(":8080", h); err != nil {
    log.Fatalf("error in ListenAndServe: %s", err)
}

func (*FS) NewRequestHandler Uses

func (fs *FS) NewRequestHandler() RequestHandler

NewRequestHandler returns new request handler with the given FS settings.

The returned handler caches requested file handles for FS.CacheDuration. Make sure your program has enough 'max open files' limit aka 'ulimit -n' if FS.Root folder contains many files.

Do not create multiple request handlers from a single FS instance - just reuse a single request handler.

type HijackHandler Uses

type HijackHandler func(c net.Conn)

HijackHandler must process the hijacked connection c.

The connection c is automatically closed after returning from HijackHandler.

The connection c must not be used after returning from the handler.

type HostClient Uses

type HostClient struct {

    // Comma-separated list of upstream HTTP server host addresses,
    // which are passed to Dial in a round-robin manner.
    //
    // Each address may contain port if default dialer is used.
    // For example,
    //
    //    - foobar.com:80
    //    - foobar.com:443
    //    - foobar.com:8080
    Addr string

    // Client name. Used in User-Agent request header.
    Name string

    // Callback for establishing new connection to the host.
    //
    // Default Dial is used if not set.
    Dial DialFunc

    // Attempt to connect to both ipv4 and ipv6 host addresses
    // if set to true.
    //
    // This option is used only if default TCP dialer is used,
    // i.e. if Dial is blank.
    //
    // By default client connects only to ipv4 addresses,
    // since unfortunately ipv6 remains broken in many networks worldwide :)
    DialDualStack bool

    // Whether to use TLS (aka SSL or HTTPS) for host connections.
    IsTLS bool

    // Optional TLS config.
    TLSConfig *tls.Config

    // Maximum number of connections which may be established to all hosts
    // listed in Addr.
    //
    // DefaultMaxConnsPerHost is used if not set.
    MaxConns int

    // Keep-alive connections are closed after this duration.
    //
    // By default connection duration is unlimited.
    MaxConnDuration time.Duration

    // Idle keep-alive connections are closed after this duration.
    //
    // By default idle connections are closed
    // after DefaultMaxIdleConnDuration.
    MaxIdleConnDuration time.Duration

    // Per-connection buffer size for responses' reading.
    // This also limits the maximum header size.
    //
    // Default buffer size is used if 0.
    ReadBufferSize int

    // Per-connection buffer size for requests' writing.
    //
    // Default buffer size is used if 0.
    WriteBufferSize int

    // Maximum duration for full response reading (including body).
    //
    // By default response read timeout is unlimited.
    ReadTimeout time.Duration

    // Maximum duration for full request writing (including body).
    //
    // By default request write timeout is unlimited.
    WriteTimeout time.Duration

    // Maximum response body size.
    //
    // The client returns ErrBodyTooLarge if this limit is greater than 0
    // and response body is greater than the limit.
    //
    // By default response body size is unlimited.
    MaxResponseBodySize int

    // Header names are passed as-is without normalization
    // if this option is set.
    //
    // Disabled header names' normalization may be useful only for proxying
    // responses to other clients expecting case-sensitive
    // header names. See https://github.com/valyala/fasthttp/issues/57
    // for details.
    //
    // By default request and response header names are normalized, i.e.
    // The first letter and the first letters following dashes
    // are uppercased, while all the other letters are lowercased.
    // Examples:
    //
    //     * HOST -> Host
    //     * content-type -> Content-Type
    //     * cONTENT-lenGTH -> Content-Length
    DisableHeaderNamesNormalizing bool
    // contains filtered or unexported fields
}

HostClient balances http requests among hosts listed in Addr.

HostClient may be used for balancing load among multiple upstream hosts. While multiple addresses passed to HostClient.Addr may be used for balancing load among them, it would be better using LBClient instead, since HostClient may unevenly balance load among upstream hosts.

It is forbidden copying HostClient instances. Create new instances instead.

It is safe calling HostClient methods from concurrently running goroutines.

Code:

package main

import (
    "log"

    "github.com/valyala/fasthttp"
)

func main() {
    // Perpare a client, which fetches webpages via HTTP proxy listening
    // on the localhost:8080.
    c := &fasthttp.HostClient{
        Addr: "localhost:8080",
    }

    // Fetch google page via local proxy.
    statusCode, body, err := c.Get(nil, "http://google.com/foo/bar")
    if err != nil {
        log.Fatalf("Error when loading google page through local proxy: %s", err)
    }
    if statusCode != fasthttp.StatusOK {
        log.Fatalf("Unexpected status code: %d. Expecting %d", statusCode, fasthttp.StatusOK)
    }
    useResponseBody(body)

    // Fetch foobar page via local proxy. Reuse body buffer.
    statusCode, body, err = c.Get(body, "http://foobar.com/google/com")
    if err != nil {
        log.Fatalf("Error when loading foobar page through local proxy: %s", err)
    }
    if statusCode != fasthttp.StatusOK {
        log.Fatalf("Unexpected status code: %d. Expecting %d", statusCode, fasthttp.StatusOK)
    }
    useResponseBody(body)
}

func useResponseBody(body []byte) {
    // Do something with body :)
}

func (*HostClient) Do Uses

func (c *HostClient) Do(req *Request, resp *Response) error

Do performs the given http request and sets the corresponding response.

Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.

The function doesn't follow redirects. Use Get* for following redirects.

Response is ignored if resp is nil.

ErrNoFreeConns is returned if all HostClient.MaxConns connections to the host are busy.

It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.

func (*HostClient) DoDeadline Uses

func (c *HostClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error

DoDeadline performs the given request and waits for response until the given deadline.

Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.

The function doesn't follow redirects. Use Get* for following redirects.

Response is ignored if resp is nil.

ErrTimeout is returned if the response wasn't returned until the given deadline.

ErrNoFreeConns is returned if all HostClient.MaxConns connections to the host are busy.

It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.

func (*HostClient) DoTimeout Uses

func (c *HostClient) DoTimeout(req *Request, resp *Response, timeout time.Duration) error

DoTimeout performs the given request and waits for response during the given timeout duration.

Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.

The function doesn't follow redirects. Use Get* for following redirects.

Response is ignored if resp is nil.

ErrTimeout is returned if the response wasn't returned during the given timeout.

ErrNoFreeConns is returned if all HostClient.MaxConns connections to the host are busy.

/ It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.

func (*HostClient) Get Uses

func (c *HostClient) Get(dst []byte, url string) (statusCode int, body []byte, err error)

Get appends url contents to dst and returns it as body.

The function follows redirects. Use Do* for manually handling redirects.

New body buffer is allocated if dst is nil.

func (*HostClient) GetDeadline Uses

func (c *HostClient) GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error)

GetDeadline appends url contents to dst and returns it as body.

The function follows redirects. Use Do* for manually handling redirects.

New body buffer is allocated if dst is nil.

ErrTimeout error is returned if url contents couldn't be fetched until the given deadline.

func (*HostClient) GetTimeout Uses

func (c *HostClient) GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error)

GetTimeout appends url contents to dst and returns it as body.

The function follows redirects. Use Do* for manually handling redirects.

New body buffer is allocated if dst is nil.

ErrTimeout error is returned if url contents couldn't be fetched during the given timeout.

func (*HostClient) LastUseTime Uses

func (c *HostClient) LastUseTime() time.Time

LastUseTime returns time the client was last used

func (*HostClient) PendingRequests Uses

func (c *HostClient) PendingRequests() int

PendingRequests returns the current number of requests the client is executing.

This function may be used for balancing load among multiple HostClient instances.

func (*HostClient) Post Uses

func (c *HostClient) Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error)

Post sends POST request to the given url with the given POST arguments.

Response body is appended to dst, which is returned as body.

The function follows redirects. Use Do* for manually handling redirects.

New body buffer is allocated if dst is nil.

Empty POST body is sent if postArgs is nil.

type LBClient Uses

type LBClient struct {

    // Clients must contain non-zero clients list.
    // Incoming requests are balanced among these clients.
    Clients []BalancingClient

    // HealthCheck is a callback called after each request.
    //
    // The request, response and the error returned by the client
    // is passed to HealthCheck, so the callback may determine whether
    // the client is healthy.
    //
    // Load on the current client is decreased if HealthCheck returns false.
    //
    // By default HealthCheck returns false if err != nil.
    HealthCheck func(req *Request, resp *Response, err error) bool

    // Timeout is the request timeout used when calling LBClient.Do.
    //
    // DefaultLBClientTimeout is used by default.
    Timeout time.Duration
    // contains filtered or unexported fields
}

LBClient balances requests among available LBClient.Clients.

It has the following features:

- Balances load among available clients using 'least loaded' + 'round robin'
  hybrid technique.
- Dynamically decreases load on unhealthy clients.

It is forbidden copying LBClient instances. Create new instances instead.

It is safe calling LBClient methods from concurrently running goroutines.

Code:

// Requests will be spread among these servers.
servers := []string{
    "google.com:80",
    "foobar.com:8080",
    "127.0.0.1:123",
}

// Prepare clients for each server
var lbc fasthttp.LBClient
for _, addr := range servers {
    c := &fasthttp.HostClient{
        Addr: addr,
    }
    lbc.Clients = append(lbc.Clients, c)
}

// Send requests to load-balanced servers
var req fasthttp.Request
var resp fasthttp.Response
for i := 0; i < 10; i++ {
    url := fmt.Sprintf("http://abcedfg/foo/bar/%d", i)
    req.SetRequestURI(url)
    if err := lbc.Do(&req, &resp); err != nil {
        log.Fatalf("Error when sending request: %s", err)
    }
    if resp.StatusCode() != fasthttp.StatusOK {
        log.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), fasthttp.StatusOK)
    }

    useResponseBody(resp.Body())
}

func (*LBClient) Do Uses

func (cc *LBClient) Do(req *Request, resp *Response) error

Do calls calculates deadline using LBClient.Timeout and calls DoDeadline on the least loaded client.

func (*LBClient) DoDeadline Uses

func (cc *LBClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error

DoDeadline calls DoDeadline on the least loaded client

func (*LBClient) DoTimeout Uses

func (cc *LBClient) DoTimeout(req *Request, resp *Response, timeout time.Duration) error

DoTimeout calculates deadline and calls DoDeadline on the least loaded client

type Logger Uses

type Logger interface {
    // Printf must have the same semantics as log.Printf.
    Printf(format string, args ...interface{})
}

Logger is used for logging formatted messages.

type PathRewriteFunc Uses

type PathRewriteFunc func(ctx *RequestCtx) []byte

PathRewriteFunc must return new request path based on arbitrary ctx info such as ctx.Path().

Path rewriter is used in FS for translating the current request to the local filesystem path relative to FS.Root.

The returned path must not contain '/../' substrings due to security reasons, since such paths may refer files outside FS.Root.

The returned path may refer to ctx members. For example, ctx.Path().

func NewPathPrefixStripper Uses

func NewPathPrefixStripper(prefixSize int) PathRewriteFunc

NewPathPrefixStripper returns path rewriter, which removes prefixSize bytes from the path prefix.

Examples:

* prefixSize = 0, original path: "/foo/bar", result: "/foo/bar"
* prefixSize = 3, original path: "/foo/bar", result: "o/bar"
* prefixSize = 7, original path: "/foo/bar", result: "r"

The returned path rewriter may be used as FS.PathRewrite .

func NewPathSlashesStripper Uses

func NewPathSlashesStripper(slashesCount int) PathRewriteFunc

NewPathSlashesStripper returns path rewriter, which strips slashesCount leading slashes from the path.

Examples:

* slashesCount = 0, original path: "/foo/bar", result: "/foo/bar"
* slashesCount = 1, original path: "/foo/bar", result: "/bar"
* slashesCount = 2, original path: "/foo/bar", result: ""

The returned path rewriter may be used as FS.PathRewrite .

func NewVHostPathRewriter Uses

func NewVHostPathRewriter(slashesCount int) PathRewriteFunc

NewVHostPathRewriter returns path rewriter, which strips slashesCount leading slashes from the path and prepends the path with request's host, thus simplifying virtual hosting for static files.

Examples:

* host=foobar.com, slashesCount=0, original path="/foo/bar".
  Resulting path: "/foobar.com/foo/bar"

* host=img.aaa.com, slashesCount=1, original path="/images/123/456.jpg"
  Resulting path: "/img.aaa.com/123/456.jpg"

type PipelineClient Uses

type PipelineClient struct {

    // Address of the host to connect to.
    Addr string

    // The maximum number of concurrent connections to the Addr.
    //
    // A sinle connection is used by default.
    MaxConns int

    // The maximum number of pending pipelined requests over
    // a single connection to Addr.
    //
    // DefaultMaxPendingRequests is used by default.
    MaxPendingRequests int

    // The maximum delay before sending pipelined requests as a batch
    // to the server.
    //
    // By default requests are sent immediately to the server.
    MaxBatchDelay time.Duration

    // Callback for connection establishing to the host.
    //
    // Default Dial is used if not set.
    Dial DialFunc

    // Attempt to connect to both ipv4 and ipv6 host addresses
    // if set to true.
    //
    // This option is used only if default TCP dialer is used,
    // i.e. if Dial is blank.
    //
    // By default client connects only to ipv4 addresses,
    // since unfortunately ipv6 remains broken in many networks worldwide :)
    DialDualStack bool

    // Whether to use TLS (aka SSL or HTTPS) for host connections.
    IsTLS bool

    // Optional TLS config.
    TLSConfig *tls.Config

    // Idle connection to the host is closed after this duration.
    //
    // By default idle connection is closed after
    // DefaultMaxIdleConnDuration.
    MaxIdleConnDuration time.Duration

    // Buffer size for responses' reading.
    // This also limits the maximum header size.
    //
    // Default buffer size is used if 0.
    ReadBufferSize int

    // Buffer size for requests' writing.
    //
    // Default buffer size is used if 0.
    WriteBufferSize int

    // Maximum duration for full response reading (including body).
    //
    // By default response read timeout is unlimited.
    ReadTimeout time.Duration

    // Maximum duration for full request writing (including body).
    //
    // By default request write timeout is unlimited.
    WriteTimeout time.Duration

    // Logger for logging client errors.
    //
    // By default standard logger from log package is used.
    Logger Logger
    // contains filtered or unexported fields
}

PipelineClient pipelines requests over a limited set of concurrent connections to the given Addr.

This client may be used in highly loaded HTTP-based RPC systems for reducing context switches and network level overhead. See https://en.wikipedia.org/wiki/HTTP_pipelining for details.

It is forbidden copying PipelineClient instances. Create new instances instead.

It is safe calling PipelineClient methods from concurrently running goroutines.

func (*PipelineClient) Do Uses

func (c *PipelineClient) Do(req *Request, resp *Response) error

Do performs the given http request and sets the corresponding response.

Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.

The function doesn't follow redirects. Use Get* for following redirects.

Response is ignored if resp is nil.

It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.

func (*PipelineClient) DoDeadline Uses

func (c *PipelineClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error

DoDeadline performs the given request and waits for response until the given deadline.

Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.

The function doesn't follow redirects.

Response is ignored if resp is nil.

ErrTimeout is returned if the response wasn't returned until the given deadline.

It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.

func (*PipelineClient) DoTimeout Uses

func (c *PipelineClient) DoTimeout(req *Request, resp *Response, timeout time.Duration) error

DoTimeout performs the given request and waits for response during the given timeout duration.

Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.

The function doesn't follow redirects.

Response is ignored if resp is nil.

ErrTimeout is returned if the response wasn't returned during the given timeout.

It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.

func (*PipelineClient) PendingRequests Uses

func (c *PipelineClient) PendingRequests() int

PendingRequests returns the current number of pending requests pipelined to the server.

This number may exceed MaxPendingRequests*MaxConns by up to two times, since each connection to the server may keep up to MaxPendingRequests requests in the queue before sending them to the server.

This function may be used for balancing load among multiple PipelineClient instances.

type Request Uses

type Request struct {

    // Request header
    //
    // Copying Header by value is forbidden. Use pointer to Header instead.
    Header RequestHeader
    // contains filtered or unexported fields
}

Request represents HTTP request.

It is forbidden copying Request instances. Create new instances and use CopyTo instead.

Request instance MUST NOT be used from concurrently running goroutines.

func AcquireRequest Uses

func AcquireRequest() *Request

AcquireRequest returns an empty Request instance from request pool.

The returned Request instance may be passed to ReleaseRequest when it is no longer needed. This allows Request recycling, reduces GC pressure and usually improves performance.

func (*Request) AppendBody Uses

func (req *Request) AppendBody(p []byte)

AppendBody appends p to request body.

It is safe re-using p after the function returns.

func (*Request) AppendBodyString Uses

func (req *Request) AppendBodyString(s string)

AppendBodyString appends s to request body.

func (*Request) Body Uses

func (req *Request) Body() []byte

Body returns request body.

func (*Request) BodyGunzip Uses

func (req *Request) BodyGunzip() ([]byte, error)

BodyGunzip returns un-gzipped body data.

This method may be used if the request header contains 'Content-Encoding: gzip' for reading un-gzipped body. Use Body for reading gzipped request body.

func (*Request) BodyInflate Uses

func (req *Request) BodyInflate() ([]byte, error)

BodyInflate returns inflated body data.

This method may be used if the response header contains 'Content-Encoding: deflate' for reading inflated request body. Use Body for reading deflated request body.

func (*Request) BodyWriteTo Uses

func (req *Request) BodyWriteTo(w io.Writer) error

BodyWriteTo writes request body to w.

func (*Request) BodyWriter Uses

func (req *Request) BodyWriter() io.Writer

BodyWriter returns writer for populating request body.

func (*Request) ConnectionClose Uses

func (req *Request) ConnectionClose() bool

ConnectionClose returns true if 'Connection: close' header is set.

func (*Request) ContinueReadBody Uses

func (req *Request) ContinueReadBody(r *bufio.Reader, maxBodySize int) error

ContinueReadBody reads request body if request header contains 'Expect: 100-continue'.

The caller must send StatusContinue response before calling this method.

If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned.

func (*Request) CopyTo Uses

func (req *Request) CopyTo(dst *Request)

CopyTo copies req contents to dst except of body stream.

func (*Request) Host Uses

func (req *Request) Host() []byte

Host returns the host for the given request.

func (*Request) IsBodyStream Uses

func (req *Request) IsBodyStream() bool

IsBodyStream returns true if body is set via SetBodyStream*

func (*Request) MayContinue Uses

func (req *Request) MayContinue() bool

MayContinue returns true if the request contains 'Expect: 100-continue' header.

The caller must do one of the following actions if MayContinue returns true:

- Either send StatusExpectationFailed response if request headers don't
  satisfy the caller.
- Or send StatusContinue response before reading request body
  with ContinueReadBody.
- Or close the connection.

func (*Request) MultipartForm Uses

func (req *Request) MultipartForm() (*multipart.Form, error)

MultipartForm returns requests's multipart form.

Returns ErrNoMultipartForm if request's Content-Type isn't 'multipart/form-data'.

RemoveMultipartFormFiles must be called after returned multipart form is processed.

func (*Request) PostArgs Uses

func (req *Request) PostArgs() *Args

PostArgs returns POST arguments.

func (*Request) Read Uses

func (req *Request) Read(r *bufio.Reader) error

Read reads request (including body) from the given r.

RemoveMultipartFormFiles or Reset must be called after reading multipart/form-data request in order to delete temporarily uploaded files.

If MayContinue returns true, the caller must:

- Either send StatusExpectationFailed response if request headers don't
  satisfy the caller.
- Or send StatusContinue response before reading request body
  with ContinueReadBody.
- Or close the connection.

io.EOF is returned if r is closed before reading the first header byte.

func (*Request) ReadLimitBody Uses

func (req *Request) ReadLimitBody(r *bufio.Reader, maxBodySize int) error

ReadLimitBody reads request from the given r, limiting the body size.

If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned.

RemoveMultipartFormFiles or Reset must be called after reading multipart/form-data request in order to delete temporarily uploaded files.

If MayContinue returns true, the caller must:

- Either send StatusExpectationFailed response if request headers don't
  satisfy the caller.
- Or send StatusContinue response before reading request body
  with ContinueReadBody.
- Or close the connection.

io.EOF is returned if r is closed before reading the first header byte.

func (*Request) ReleaseBody Uses

func (req *Request) ReleaseBody(size int)

ReleaseBody retires the request body if it is greater than "size" bytes.

This permits GC to reclaim the large buffer. If used, must be before ReleaseRequest.

Use this method only if you really understand how it works. The majority of workloads don't need this method.

func (*Request) RemoveMultipartFormFiles Uses

func (req *Request) RemoveMultipartFormFiles()

RemoveMultipartFormFiles removes multipart/form-data temporary files associated with the request.

func (*Request) RequestURI Uses

func (req *Request) RequestURI() []byte

RequestURI returns request's URI.

func (*Request) Reset Uses

func (req *Request) Reset()

Reset clears request contents.

func (*Request) ResetBody Uses

func (req *Request) ResetBody()

ResetBody resets request body.

func (*Request) SetBody Uses

func (req *Request) SetBody(body []byte)

SetBody sets request body.

It is safe re-using body argument after the function returns.

func (*Request) SetBodyStream Uses

func (req *Request) SetBodyStream(bodyStream io.Reader, bodySize int)

SetBodyStream sets request body stream and, optionally body size.

If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes before returning io.EOF.

If bodySize < 0, then bodyStream is read until io.EOF.

bodyStream.Close() is called after finishing reading all body data if it implements io.Closer.

Note that GET and HEAD requests cannot have body.

See also SetBodyStreamWriter.

func (*Request) SetBodyStreamWriter Uses

func (req *Request) SetBodyStreamWriter(sw StreamWriter)

SetBodyStreamWriter registers the given sw for populating request body.

This function may be used in the following cases:

* if request body is too big (more than 10MB).
* if request body is streamed from slow external sources.
* if request body must be streamed to the server in chunks
(aka `http client push` or `chunked transfer-encoding`).

Note that GET and HEAD requests cannot have body.

/ See also SetBodyStream.

func (*Request) SetBodyString Uses

func (req *Request) SetBodyString(body string)

SetBodyString sets request body.

func (*Request) SetConnectionClose Uses

func (req *Request) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*Request) SetHost Uses

func (req *Request) SetHost(host string)

SetHost sets host for the request.

func (*Request) SetHostBytes Uses

func (req *Request) SetHostBytes(host []byte)

SetHostBytes sets host for the request.

func (*Request) SetRequestURI Uses

func (req *Request) SetRequestURI(requestURI string)

SetRequestURI sets RequestURI.

func (*Request) SetRequestURIBytes Uses

func (req *Request) SetRequestURIBytes(requestURI []byte)

SetRequestURIBytes sets RequestURI.

func (*Request) String Uses

func (req *Request) String() string

String returns request representation.

Returns error message instead of request representation on error.

Use Write instead of String for performance-critical code.

func (*Request) SwapBody Uses

func (req *Request) SwapBody(body []byte) []byte

SwapBody swaps request body with the given body and returns the previous request body.

It is forbidden to use the body passed to SwapBody after the function returns.

func (*Request) URI Uses

func (req *Request) URI() *URI

URI returns request URI

func (*Request) Write Uses

func (req *Request) Write(w *bufio.Writer) error

Write writes request to w.

Write doesn't flush request to w for performance reasons.

See also WriteTo.

func (*Request) WriteTo Uses

func (req *Request) WriteTo(w io.Writer) (int64, error)

WriteTo writes request to w. It implements io.WriterTo.

type RequestCtx Uses

type RequestCtx struct {

    // Incoming request.
    //
    // Copying Request by value is forbidden. Use pointer to Request instead.
    Request Request

    // Outgoing response.
    //
    // Copying Response by value is forbidden. Use pointer to Response instead.
    Response Response
    // contains filtered or unexported fields
}

RequestCtx contains incoming request and manages outgoing response.

It is forbidden copying RequestCtx instances.

RequestHandler should avoid holding references to incoming RequestCtx and/or its' members after the return. If holding RequestCtx references after the return is unavoidable (for instance, ctx is passed to a separate goroutine and ctx lifetime cannot be controlled), then the RequestHandler MUST call ctx.TimeoutError() before return.

It is unsafe modifying/reading RequestCtx instance from concurrently running goroutines. The only exception is TimeoutError*, which may be called while other goroutines accessing RequestCtx.

func (*RequestCtx) ConnID Uses

func (ctx *RequestCtx) ConnID() uint64

ConnID returns unique connection ID.

This ID may be used to match distinct requests to the same incoming connection.

func (*RequestCtx) ConnRequestNum Uses

func (ctx *RequestCtx) ConnRequestNum() uint64

ConnRequestNum returns request sequence number for the current connection.

Sequence starts with 1.

func (*RequestCtx) ConnTime Uses

func (ctx *RequestCtx) ConnTime() time.Time

ConnTime returns the time server starts serving the connection the current request came from.

The returned time is truncated to the nearest second.

func (*RequestCtx) Error Uses

func (ctx *RequestCtx) Error(msg string, statusCode int)

Error sets response status code to the given value and sets response body to the given message.

func (*RequestCtx) FormFile Uses

func (ctx *RequestCtx) FormFile(key string) (*multipart.FileHeader, error)

FormFile returns uploaded file associated with the given multipart form key.

The file is automatically deleted after returning from RequestHandler, so either move or copy uploaded file into new place if you want retaining it.

Use SaveMultipartFile function for permanently saving uploaded file.

The returned file header is valid until returning from RequestHandler.

func (*RequestCtx) FormValue Uses

func (ctx *RequestCtx) FormValue(key string) []byte

FormValue returns form value associated with the given key.

The value is searched in the following places:

* Query string.
* POST or PUT body.

There are more fine-grained methods for obtaining form values:

* QueryArgs for obtaining values from query string.
* PostArgs for obtaining values from POST or PUT body.
* MultipartForm for obtaining values from multipart form.
* FormFile for obtaining uploaded files.

The returned value is valid until returning from RequestHandler.

func (*RequestCtx) Hijack Uses

func (ctx *RequestCtx) Hijack(handler HijackHandler)

Hijack registers the given handler for connection hijacking.

The handler is called after returning from RequestHandler and sending http response. The current connection is passed to the handler. The connection is automatically closed after returning from the handler.

The server skips calling the handler in the following cases:

* 'Connection: close' header exists in either request or response.
* Unexpected error during response writing to the connection.

The server stops processing requests from hijacked connections. Server limits such as Concurrency, ReadTimeout, WriteTimeout, etc. aren't applied to hijacked connections.

The handler must not retain references to ctx members.

Arbitrary 'Connection: Upgrade' protocols may be implemented with HijackHandler. For instance,

* WebSocket ( https://en.wikipedia.org/wiki/WebSocket )
* HTTP/2.0 ( https://en.wikipedia.org/wiki/HTTP/2 )

Code:

// hijackHandler is called on hijacked connection.
hijackHandler := func(c net.Conn) {
    fmt.Fprintf(c, "This message is sent over a hijacked connection to the client %s\n", c.RemoteAddr())
    fmt.Fprintf(c, "Send me something and I'll echo it to you\n")
    var buf [1]byte
    for {
        if _, err := c.Read(buf[:]); err != nil {
            log.Printf("error when reading from hijacked connection: %s", err)
            return
        }
        fmt.Fprintf(c, "You sent me %q. Waiting for new data\n", buf[:])
    }
}

// requestHandler is called for each incoming request.
requestHandler := func(ctx *fasthttp.RequestCtx) {
    path := ctx.Path()
    switch {
    case string(path) == "/hijack":
        // Note that the connection is hijacked only after
        // returning from requestHandler and sending http response.
        ctx.Hijack(hijackHandler)

        // The connection will be hijacked after sending this response.
        fmt.Fprintf(ctx, "Hijacked the connection!")
    case string(path) == "/":
        fmt.Fprintf(ctx, "Root directory requested")
    default:
        fmt.Fprintf(ctx, "Requested path is %q", path)
    }
}

if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil {
    log.Fatalf("error in ListenAndServe: %s", err)
}

func (*RequestCtx) Hijacked Uses

func (ctx *RequestCtx) Hijacked() bool

Hijacked returns true after Hijack is called.

func (*RequestCtx) Host Uses

func (ctx *RequestCtx) Host() []byte

Host returns requested host.

The host is valid until returning from RequestHandler.

func (*RequestCtx) ID Uses

func (ctx *RequestCtx) ID() uint64

ID returns unique ID of the request.

func (*RequestCtx) IfModifiedSince Uses

func (ctx *RequestCtx) IfModifiedSince(lastModified time.Time) bool

IfModifiedSince returns true if lastModified exceeds 'If-Modified-Since' value from the request header.

The function returns true also 'If-Modified-Since' request header is missing.

func (*RequestCtx) Init Uses

func (ctx *RequestCtx) Init(req *Request, remoteAddr net.Addr, logger Logger)

Init prepares ctx for passing to RequestHandler.

remoteAddr and logger are optional. They are used by RequestCtx.Logger().

This function is intended for custom Server implementations.

func (*RequestCtx) Init2 Uses

func (ctx *RequestCtx) Init2(conn net.Conn, logger Logger, reduceMemoryUsage bool)

Init2 prepares ctx for passing to RequestHandler.

conn is used only for determining local and remote addresses.

This function is intended for custom Server implementations. See https://github.com/valyala/httpteleport for details.

func (*RequestCtx) IsBodyStream Uses

func (ctx *RequestCtx) IsBodyStream() bool

IsBodyStream returns true if response body is set via SetBodyStream*.

func (*RequestCtx) IsDelete Uses

func (ctx *RequestCtx) IsDelete() bool

IsDelete returns true if request method is DELETE.

func (*RequestCtx) IsGet Uses

func (ctx *RequestCtx) IsGet() bool

IsGet returns true if request method is GET.

func (*RequestCtx) IsHead Uses

func (ctx *RequestCtx) IsHead() bool

IsHead returns true if request method is HEAD.

func (*RequestCtx) IsPost Uses

func (ctx *RequestCtx) IsPost() bool

IsPost returns true if request method is POST.

func (*RequestCtx) IsPut Uses

func (ctx *RequestCtx) IsPut() bool

IsPut returns true if request method is PUT.

func (*RequestCtx) IsTLS Uses

func (ctx *RequestCtx) IsTLS() bool

IsTLS returns true if the underlying connection is tls.Conn.

tls.Conn is an encrypted connection (aka SSL, HTTPS).

func (*RequestCtx) LastTimeoutErrorResponse Uses

func (ctx *RequestCtx) LastTimeoutErrorResponse() *Response

LastTimeoutErrorResponse returns the last timeout response set via TimeoutError* call.

This function is intended for custom server implementations.

func (*RequestCtx) LocalAddr Uses

func (ctx *RequestCtx) LocalAddr() net.Addr

LocalAddr returns server address for the given request.

Always returns non-nil result.

func (*RequestCtx) LocalIP Uses

func (ctx *RequestCtx) LocalIP() net.IP

LocalIP returns the server ip the request came to.

Always returns non-nil result.

func (*RequestCtx) Logger Uses

func (ctx *RequestCtx) Logger() Logger

Logger returns logger, which may be used for logging arbitrary request-specific messages inside RequestHandler.

Each message logged via returned logger contains request-specific information such as request id, request duration, local address, remote address, request method and request url.

It is safe re-using returned logger for logging multiple messages for the current request.

The returned logger is valid until returning from RequestHandler.

Code:

requestHandler := func(ctx *fasthttp.RequestCtx) {
    if string(ctx.Path()) == "/top-secret" {
        ctx.Logger().Printf("Alarm! Alien intrusion detected!")
        ctx.Error("Access denied!", fasthttp.StatusForbidden)
        return
    }

    // Logger may be cached in local variables.
    logger := ctx.Logger()

    logger.Printf("Good request from User-Agent %q", ctx.Request.Header.UserAgent())
    fmt.Fprintf(ctx, "Good request to %q", ctx.Path())
    logger.Printf("Multiple log messages may be written during a single request")
}

if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil {
    log.Fatalf("error in ListenAndServe: %s", err)
}

func (*RequestCtx) Method Uses

func (ctx *RequestCtx) Method() []byte

Method return request method.

Returned value is valid until returning from RequestHandler.

func (*RequestCtx) MultipartForm Uses

func (ctx *RequestCtx) MultipartForm() (*multipart.Form, error)

MultipartForm returns requests's multipart form.

Returns ErrNoMultipartForm if request's content-type isn't 'multipart/form-data'.

All uploaded temporary files are automatically deleted after returning from RequestHandler. Either move or copy uploaded files into new place if you want retaining them.

Use SaveMultipartFile function for permanently saving uploaded file.

The returned form is valid until returning from RequestHandler.

See also FormFile and FormValue.

func (*RequestCtx) NotFound Uses

func (ctx *RequestCtx) NotFound()

NotFound resets response and sets '404 Not Found' response status code.

func (*RequestCtx) NotModified Uses

func (ctx *RequestCtx) NotModified()

NotModified resets response and sets '304 Not Modified' response status code.

func (*RequestCtx) Path Uses

func (ctx *RequestCtx) Path() []byte

Path returns requested path.

The path is valid until returning from RequestHandler.

func (*RequestCtx) PostArgs Uses

func (ctx *RequestCtx) PostArgs() *Args

PostArgs returns POST arguments.

It doesn't return query arguments from RequestURI - use QueryArgs for this.

Returned arguments are valid until returning from RequestHandler.

See also QueryArgs, FormValue and FormFile.

func (*RequestCtx) PostBody Uses

func (ctx *RequestCtx) PostBody() []byte

PostBody returns POST request body.

The returned value is valid until RequestHandler return.

func (*RequestCtx) QueryArgs Uses

func (ctx *RequestCtx) QueryArgs() *Args

QueryArgs returns query arguments from RequestURI.

It doesn't return POST'ed arguments - use PostArgs() for this.

Returned arguments are valid until returning from RequestHandler.

See also PostArgs, FormValue and FormFile.

func (*RequestCtx) Redirect Uses

func (ctx *RequestCtx) Redirect(uri string, statusCode int)

Redirect sets 'Location: uri' response header and sets the given statusCode.

statusCode must have one of the following values:

* StatusMovedPermanently (301)
* StatusFound (302)
* StatusSeeOther (303)
* StatusTemporaryRedirect (307)

All other statusCode values are replaced by StatusFound (302).

The redirect uri may be either absolute or relative to the current request uri.

func (*RequestCtx) RedirectBytes Uses

func (ctx *RequestCtx) RedirectBytes(uri []byte, statusCode int)

RedirectBytes sets 'Location: uri' response header and sets the given statusCode.

statusCode must have one of the following values:

* StatusMovedPermanently (301)
* StatusFound (302)
* StatusSeeOther (303)
* StatusTemporaryRedirect (307)

All other statusCode values are replaced by StatusFound (302).

The redirect uri may be either absolute or relative to the current request uri.

func (*RequestCtx) Referer Uses

func (ctx *RequestCtx) Referer() []byte

Referer returns request referer.

The referer is valid until returning from RequestHandler.

func (*RequestCtx) RemoteAddr Uses

func (ctx *RequestCtx) RemoteAddr() net.Addr

RemoteAddr returns client address for the given request.

Always returns non-nil result.

func (*RequestCtx) RemoteIP Uses

func (ctx *RequestCtx) RemoteIP() net.IP

RemoteIP returns the client ip the request came from.

Always returns non-nil result.

func (*RequestCtx) RequestURI Uses

func (ctx *RequestCtx) RequestURI() []byte

RequestURI returns RequestURI.

This uri is valid until returning from RequestHandler.

func (*RequestCtx) ResetBody Uses

func (ctx *RequestCtx) ResetBody()

ResetBody resets response body contents.

func (*RequestCtx) SendFile Uses

func (ctx *RequestCtx) SendFile(path string)

SendFile sends local file contents from the given path as response body.

This is a shortcut to ServeFile(ctx, path).

SendFile logs all the errors via ctx.Logger.

See also ServeFile, FSHandler and FS.

func (*RequestCtx) SendFileBytes Uses

func (ctx *RequestCtx) SendFileBytes(path []byte)

SendFileBytes sends local file contents from the given path as response body.

This is a shortcut to ServeFileBytes(ctx, path).

SendFileBytes logs all the errors via ctx.Logger.

See also ServeFileBytes, FSHandler and FS.

func (*RequestCtx) SetBody Uses

func (ctx *RequestCtx) SetBody(body []byte)

SetBody sets response body to the given value.

It is safe re-using body argument after the function returns.

func (*RequestCtx) SetBodyStream Uses

func (ctx *RequestCtx) SetBodyStream(bodyStream io.Reader, bodySize int)

SetBodyStream sets response body stream and, optionally body size.

bodyStream.Close() is called after finishing reading all body data if it implements io.Closer.

If bodySize is >= 0, then bodySize bytes must be provided by bodyStream before returning io.EOF.

If bodySize < 0, then bodyStream is read until io.EOF.

See also SetBodyStreamWriter.

func (*RequestCtx) SetBodyStreamWriter Uses

func (ctx *RequestCtx) SetBodyStreamWriter(sw StreamWriter)

SetBodyStreamWriter registers the given stream writer for populating response body.

Access to RequestCtx and/or its' members is forbidden from sw.

This function may be used in the following cases:

* if response body is too big (more than 10MB).
* if response body is streamed from slow external sources.
* if response body must be streamed to the client in chunks.
(aka `http server push`).

Code:

package main

import (
    "bufio"
    "fmt"
    "log"
    "time"

    "github.com/valyala/fasthttp"
)

func main() {
    // Start fasthttp server for streaming responses.
    if err := fasthttp.ListenAndServe(":8080", responseStreamHandler); err != nil {
        log.Fatalf("unexpected error in server: %s", err)
    }
}

func responseStreamHandler(ctx *fasthttp.RequestCtx) {
    // Send the response in chunks and wait for a second between each chunk.
    ctx.SetBodyStreamWriter(func(w *bufio.Writer) {
        for i := 0; i < 10; i++ {
            fmt.Fprintf(w, "this is a message number %d", i)

            // Do not forget flushing streamed data to the client.
            if err := w.Flush(); err != nil {
                return
            }
            time.Sleep(time.Second)
        }
    })
}

func (*RequestCtx) SetBodyString Uses

func (ctx *RequestCtx) SetBodyString(body string)

SetBodyString sets response body to the given value.

func (*RequestCtx) SetConnectionClose Uses

func (ctx *RequestCtx) SetConnectionClose()

SetConnectionClose sets 'Connection: close' response header and closes connection after the RequestHandler returns.

func (*RequestCtx) SetContentType Uses

func (ctx *RequestCtx) SetContentType(contentType string)

SetContentType sets response Content-Type.

func (*RequestCtx) SetContentTypeBytes Uses

func (ctx *RequestCtx) SetContentTypeBytes(contentType []byte)

SetContentTypeBytes sets response Content-Type.

It is safe modifying contentType buffer after function return.

func (*RequestCtx) SetStatusCode Uses

func (ctx *RequestCtx) SetStatusCode(statusCode int)

SetStatusCode sets response status code.

func (*RequestCtx) SetUserValue Uses

func (ctx *RequestCtx) SetUserValue(key string, value interface{})

SetUserValue stores the given value (arbitrary object) under the given key in ctx.

The value stored in ctx may be obtained by UserValue*.

This functionality may be useful for passing arbitrary values between functions involved in request processing.

All the values are removed from ctx after returning from the top RequestHandler. Additionally, Close method is called on each value implementing io.Closer before removing the value from ctx.

func (*RequestCtx) SetUserValueBytes Uses

func (ctx *RequestCtx) SetUserValueBytes(key []byte, value interface{})

SetUserValueBytes stores the given value (arbitrary object) under the given key in ctx.

The value stored in ctx may be obtained by UserValue*.

This functionality may be useful for passing arbitrary values between functions involved in request processing.

All the values stored in ctx are deleted after returning from RequestHandler.

func (*RequestCtx) Success Uses

func (ctx *RequestCtx) Success(contentType string, body []byte)

Success sets response Content-Type and body to the given values.

func (*RequestCtx) SuccessString Uses

func (ctx *RequestCtx) SuccessString(contentType, body string)

SuccessString sets response Content-Type and body to the given values.

func (*RequestCtx) TLSConnectionState Uses

func (ctx *RequestCtx) TLSConnectionState() *tls.ConnectionState

TLSConnectionState returns TLS connection state.

The function returns nil if the underlying connection isn't tls.Conn.

The returned state may be used for verifying TLS version, client certificates, etc.

func (*RequestCtx) Time Uses

func (ctx *RequestCtx) Time() time.Time

Time returns RequestHandler call time truncated to the nearest second.

Call time.Now() at the beginning of RequestHandler in order to obtain percise RequestHandler call time.

func (*RequestCtx) TimeoutError Uses

func (ctx *RequestCtx) TimeoutError(msg string)

TimeoutError sets response status code to StatusRequestTimeout and sets body to the given msg.

All response modifications after TimeoutError call are ignored.

TimeoutError MUST be called before returning from RequestHandler if there are references to ctx and/or its members in other goroutines remain.

Usage of this function is discouraged. Prefer eliminating ctx references from pending goroutines instead of using this function.

Code:

requestHandler := func(ctx *fasthttp.RequestCtx) {
    // Emulate long-running task, which touches ctx.
    doneCh := make(chan struct{})
    go func() {
        workDuration := time.Millisecond * time.Duration(rand.Intn(2000))
        time.Sleep(workDuration)

        fmt.Fprintf(ctx, "ctx has been accessed by long-running task\n")
        fmt.Fprintf(ctx, "The reuqestHandler may be finished by this time.\n")

        close(doneCh)
    }()

    select {
    case <-doneCh:
        fmt.Fprintf(ctx, "The task has been finished in less than a second")
    case <-time.After(time.Second):
        // Since the long-running task is still running and may access ctx,
        // we must call TimeoutError before returning from requestHandler.
        //
        // Otherwise the program will suffer from data races.
        ctx.TimeoutError("Timeout!")
    }
}

if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil {
    log.Fatalf("error in ListenAndServe: %s", err)
}

func (*RequestCtx) TimeoutErrorWithCode Uses

func (ctx *RequestCtx) TimeoutErrorWithCode(msg string, statusCode int)

TimeoutErrorWithCode sets response body to msg and response status code to statusCode.

All response modifications after TimeoutErrorWithCode call are ignored.

TimeoutErrorWithCode MUST be called before returning from RequestHandler if there are references to ctx and/or its members in other goroutines remain.

Usage of this function is discouraged. Prefer eliminating ctx references from pending goroutines instead of using this function.

func (*RequestCtx) TimeoutErrorWithResponse Uses

func (ctx *RequestCtx) TimeoutErrorWithResponse(resp *Response)

TimeoutErrorWithResponse marks the ctx as timed out and sends the given response to the client.

All ctx modifications after TimeoutErrorWithResponse call are ignored.

TimeoutErrorWithResponse MUST be called before returning from RequestHandler if there are references to ctx and/or its members in other goroutines remain.

Usage of this function is discouraged. Prefer eliminating ctx references from pending goroutines instead of using this function.

func (*RequestCtx) URI Uses

func (ctx *RequestCtx) URI() *URI

URI returns requested uri.

The uri is valid until returning from RequestHandler.

func (*RequestCtx) UserAgent Uses

func (ctx *RequestCtx) UserAgent() []byte

UserAgent returns User-Agent header value from the request.

func (*RequestCtx) UserValue Uses

func (ctx *RequestCtx) UserValue(key string) interface{}

UserValue returns the value stored via SetUserValue* under the given key.

func (*RequestCtx) UserValueBytes Uses

func (ctx *RequestCtx) UserValueBytes(key []byte) interface{}

UserValueBytes returns the value stored via SetUserValue* under the given key.

func (*RequestCtx) VisitUserValues Uses

func (ctx *RequestCtx) VisitUserValues(visitor func([]byte, interface{}))

VisitUserValues calls visitor for each existing userValue.

visitor must not retain references to key and value after returning. Make key and/or value copies if you need storing them after returning.

func (*RequestCtx) Write Uses

func (ctx *RequestCtx) Write(p []byte) (int, error)

Write writes p into response body.

func (*RequestCtx) WriteString Uses

func (ctx *RequestCtx) WriteString(s string) (int, error)

WriteString appends s to response body.

type RequestHandler Uses

type RequestHandler func(ctx *RequestCtx)

RequestHandler must process incoming requests.

RequestHandler must call ctx.TimeoutError() before returning if it keeps references to ctx and/or its' members after the return. Consider wrapping RequestHandler into TimeoutHandler if response time must be limited.

func CompressHandler Uses

func CompressHandler(h RequestHandler) RequestHandler

CompressHandler returns RequestHandler that transparently compresses response body generated by h if the request contains 'gzip' or 'deflate' 'Accept-Encoding' header.

func CompressHandlerLevel Uses

func CompressHandlerLevel(h RequestHandler, level int) RequestHandler

CompressHandlerLevel returns RequestHandler that transparently compresses response body generated by h if the request contains 'gzip' or 'deflate' 'Accept-Encoding' header.

Level is the desired compression level:

* CompressNoCompression
* CompressBestSpeed
* CompressBestCompression
* CompressDefaultCompression

func FSHandler Uses

func FSHandler(root string, stripSlashes int) RequestHandler

FSHandler returns request handler serving static files from the given root folder.

stripSlashes indicates how many leading slashes must be stripped from requested path before searching requested file in the root folder. Examples:

* stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar"
* stripSlashes = 1, original path: "/foo/bar", result: "/bar"
* stripSlashes = 2, original path: "/foo/bar", result: ""

The returned request handler automatically generates index pages for directories without index.html.

The returned handler caches requested file handles for FSHandlerCacheDuration. Make sure your program has enough 'max open files' limit aka 'ulimit -n' if root folder contains many files.

Do not create multiple request handler instances for the same (root, stripSlashes) arguments - just reuse a single instance. Otherwise goroutine leak will occur.

Code:

package main

import (
    "bytes"
    "log"

    "github.com/valyala/fasthttp"
)

// Setup file handlers (aka 'file server config')
var (
    // Handler for serving images from /img/ path,
    // i.e. /img/foo/bar.jpg will be served from
    // /var/www/images/foo/bar.jpb .
    imgPrefix  = []byte("/img/")
    imgHandler = fasthttp.FSHandler("/var/www/images", 1)

    // Handler for serving css from /static/css/ path,
    // i.e. /static/css/foo/bar.css will be served from
    // /home/dev/css/foo/bar.css .
    cssPrefix  = []byte("/static/css/")
    cssHandler = fasthttp.FSHandler("/home/dev/css", 2)

    // Handler for serving the rest of requests,
    // i.e. /foo/bar/baz.html will be served from
    // /var/www/files/foo/bar/baz.html .
    filesHandler = fasthttp.FSHandler("/var/www/files", 0)
)

// Main request handler
func requestHandler(ctx *fasthttp.RequestCtx) {
    path := ctx.Path()
    switch {
    case bytes.HasPrefix(path, imgPrefix):
        imgHandler(ctx)
    case bytes.HasPrefix(path, cssPrefix):
        cssHandler(ctx)
    default:
        filesHandler(ctx)
    }
}

func main() {
    if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil {
        log.Fatalf("Error in server: %s", err)
    }
}

func TimeoutHandler Uses

func TimeoutHandler(h RequestHandler, timeout time.Duration, msg string) RequestHandler

TimeoutHandler creates RequestHandler, which returns StatusRequestTimeout error with the given msg to the client if h didn't return during the given duration.

The returned handler may return StatusTooManyRequests error with the given msg to the client if there are more than Server.Concurrency concurrent handlers h are running at the moment.

type RequestHeader Uses

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

RequestHeader represents HTTP request header.

It is forbidden copying RequestHeader instances. Create new instances instead and use CopyTo.

RequestHeader instance MUST NOT be used from concurrently running goroutines.

func (*RequestHeader) Add Uses

func (h *RequestHeader) Add(key, value string)

Add adds the given 'key: value' header.

Multiple headers with the same key may be added with this function. Use Set for setting a single header for the given key.

func (*RequestHeader) AddBytesK Uses

func (h *RequestHeader) AddBytesK(key []byte, value string)

AddBytesK adds the given 'key: value' header.

Multiple headers with the same key may be added with this function. Use SetBytesK for setting a single header for the given key.

func (*RequestHeader) AddBytesKV Uses

func (h *RequestHeader) AddBytesKV(key, value []byte)

AddBytesKV adds the given 'key: value' header.

Multiple headers with the same key may be added with this function. Use SetBytesKV for setting a single header for the given key.

func (*RequestHeader) AddBytesV Uses

func (h *RequestHeader) AddBytesV(key string, value []byte)

AddBytesV adds the given 'key: value' header.

Multiple headers with the same key may be added with this function. Use SetBytesV for setting a single header for the given key.

func (*RequestHeader) AppendBytes Uses

func (h *RequestHeader) AppendBytes(dst []byte) []byte

AppendBytes appends request header representation to dst and returns the extended dst.

func (*RequestHeader) ConnectionClose Uses

func (h *RequestHeader) ConnectionClose() bool

ConnectionClose returns true if 'Connection: close' header is set.

func (*RequestHeader) ConnectionUpgrade Uses

func (h *RequestHeader) ConnectionUpgrade() bool

ConnectionUpgrade returns true if 'Connection: Upgrade' header is set.

func (*RequestHeader) ContentLength Uses

func (h *RequestHeader) ContentLength() int

ContentLength returns Content-Length header value.

It may be negative: -1 means Transfer-Encoding: chunked.

func (*RequestHeader) ContentType Uses

func (h *RequestHeader) ContentType() []byte

ContentType returns Content-Type header value.

func (*RequestHeader) Cookie Uses

func (h *RequestHeader) Cookie(key string) []byte

Cookie returns cookie for the given key.

func (*RequestHeader) CookieBytes Uses

func (h *RequestHeader) CookieBytes(key []byte) []byte

CookieBytes returns cookie for the given key.

func (*RequestHeader) CopyTo Uses

func (h *RequestHeader) CopyTo(dst *RequestHeader)

CopyTo copies all the headers to dst.

func (*RequestHeader) Del Uses

func (h *RequestHeader) Del(key string)

Del deletes header with the given key.

func (*RequestHeader) DelAllCookies Uses

func (h *RequestHeader) DelAllCookies()

DelAllCookies removes all the cookies from request headers.

func (*RequestHeader) DelBytes Uses

func (h *RequestHeader) DelBytes(key []byte)

DelBytes deletes header with the given key.

func (*RequestHeader) DelCookie Uses

func (h *RequestHeader) DelCookie(key string)

DelCookie removes cookie under the given key.

func (*RequestHeader) DelCookieBytes Uses

func (h *RequestHeader) DelCookieBytes(key []byte)

DelCookieBytes removes cookie under the given key.

func (*RequestHeader) DisableNormalizing Uses

func (h *RequestHeader) DisableNormalizing()

DisableNormalizing disables header names' normalization.

By default all the header names are normalized by uppercasing the first letter and all the first letters following dashes, while lowercasing all the other letters. Examples:

* CONNECTION -> Connection
* conteNT-tYPE -> Content-Type
* foo-bar-baz -> Foo-Bar-Baz

Disable header names' normalization only if know what are you doing.

func (*RequestHeader) HasAcceptEncoding Uses

func (h *RequestHeader) HasAcceptEncoding(acceptEncoding string) bool

HasAcceptEncoding returns true if the header contains the given Accept-Encoding value.

func (*RequestHeader) HasAcceptEncodingBytes Uses

func (h *RequestHeader) HasAcceptEncodingBytes(acceptEncoding []byte) bool

HasAcceptEncodingBytes returns true if the header contains the given Accept-Encoding value.

func (*RequestHeader) Header Uses

func (h *RequestHeader) Header() []byte

Header returns request header representation.

The returned representation is valid until the next call to RequestHeader methods.

func (*RequestHeader) Host Uses

func (h *RequestHeader) Host() []byte

Host returns Host header value.

func (*RequestHeader) IsDelete Uses

func (h *RequestHeader) IsDelete() bool

IsDelete returns true if request method is DELETE.

func (*RequestHeader) IsGet Uses

func (h *RequestHeader) IsGet() bool

IsGet returns true if request method is GET.

func (*RequestHeader) IsHTTP11 Uses

func (h *RequestHeader) IsHTTP11() bool

IsHTTP11 returns true if the request is HTTP/1.1.

func (*RequestHeader) IsHead Uses

func (h *RequestHeader) IsHead() bool

IsHead returns true if request method is HEAD.

func (*RequestHeader) IsPost Uses

func (h *RequestHeader) IsPost() bool

IsPost returns true if request methos is POST.

func (*RequestHeader) IsPut Uses

func (h *RequestHeader) IsPut() bool

IsPut returns true if request method is PUT.

func (*RequestHeader) Len Uses

func (h *RequestHeader) Len() int

Len returns the number of headers set, i.e. the number of times f is called in VisitAll.

func (*RequestHeader) Method Uses

func (h *RequestHeader) Method() []byte

Method returns HTTP request method.

func (*RequestHeader) MultipartFormBoundary Uses

func (h *RequestHeader) MultipartFormBoundary() []byte

MultipartFormBoundary returns boundary part from 'multipart/form-data; boundary=...' Content-Type.

func (*RequestHeader) Peek Uses

func (h *RequestHeader) Peek(key string) []byte

Peek returns header value for the given key.

Returned value is valid until the next call to RequestHeader. Do not store references to returned value. Make copies instead.

func (*RequestHeader) PeekBytes Uses

func (h *RequestHeader) PeekBytes(key []byte) []byte

PeekBytes returns header value for the given key.

Returned value is valid until the next call to RequestHeader. Do not store references to returned value. Make copies instead.

func (*RequestHeader) Read Uses

func (h *RequestHeader) Read(r *bufio.Reader) error

Read reads request header from r.

io.EOF is returned if r is closed before reading the first header byte.

func (*RequestHeader) Referer Uses

func (h *RequestHeader) Referer() []byte

Referer returns Referer header value.

func (*RequestHeader) RequestURI Uses

func (h *RequestHeader) RequestURI() []byte

RequestURI returns RequestURI from the first HTTP request line.

func (*RequestHeader) Reset Uses

func (h *RequestHeader) Reset()

Reset clears request header.

func (*RequestHeader) ResetConnectionClose Uses

func (h *RequestHeader) ResetConnectionClose()

ResetConnectionClose clears 'Connection: close' header if it exists.

func (*RequestHeader) Set Uses

func (h *RequestHeader) Set(key, value string)

Set sets the given 'key: value' header.

Use Add for setting multiple header values under the same key.

func (*RequestHeader) SetByteRange Uses

func (h *RequestHeader) SetByteRange(startPos, endPos int)

SetByteRange sets 'Range: bytes=startPos-endPos' header.

* If startPos is negative, then 'bytes=-startPos' value is set.
* If endPos is negative, then 'bytes=startPos-' value is set.

func (*RequestHeader) SetBytesK Uses

func (h *RequestHeader) SetBytesK(key []byte, value string)

SetBytesK sets the given 'key: value' header.

Use AddBytesK for setting multiple header values under the same key.

func (*RequestHeader) SetBytesKV Uses

func (h *RequestHeader) SetBytesKV(key, value []byte)

SetBytesKV sets the given 'key: value' header.

Use AddBytesKV for setting multiple header values under the same key.

func (*RequestHeader) SetBytesV Uses

func (h *RequestHeader) SetBytesV(key string, value []byte)

SetBytesV sets the given 'key: value' header.

Use AddBytesV for setting multiple header values under the same key.

func (*RequestHeader) SetCanonical Uses

func (h *RequestHeader) SetCanonical(key, value []byte)

SetCanonical sets the given 'key: value' header assuming that key is in canonical form.

func (*RequestHeader) SetConnectionClose Uses

func (h *RequestHeader) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*RequestHeader) SetContentLength Uses

func (h *RequestHeader) SetContentLength(contentLength int)

SetContentLength sets Content-Length header value.

Negative content-length sets 'Transfer-Encoding: chunked' header.

func (*RequestHeader) SetContentType Uses

func (h *RequestHeader) SetContentType(contentType string)

SetContentType sets Content-Type header value.

func (*RequestHeader) SetContentTypeBytes Uses

func (h *RequestHeader) SetContentTypeBytes(contentType []byte)

SetContentTypeBytes sets Content-Type header value.

func (*RequestHeader) SetCookie Uses

func (h *RequestHeader) SetCookie(key, value string)

SetCookie sets 'key: value' cookies.

func (*RequestHeader) SetCookieBytesK Uses

func (h *RequestHeader) SetCookieBytesK(key []byte, value string)

SetCookieBytesK sets 'key: value' cookies.

func (*RequestHeader) SetCookieBytesKV Uses

func (h *RequestHeader) SetCookieBytesKV(key, value []byte)

SetCookieBytesKV sets 'key: value' cookies.

func (*RequestHeader) SetHost Uses

func (h *RequestHeader) SetHost(host string)

SetHost sets Host header value.

func (*RequestHeader) SetHostBytes Uses

func (h *RequestHeader) SetHostBytes(host []byte)

SetHostBytes sets Host header value.

func (*RequestHeader) SetMethod Uses

func (h *RequestHeader) SetMethod(method string)

SetMethod sets HTTP request method.

func (*RequestHeader) SetMethodBytes Uses

func (h *RequestHeader) SetMethodBytes(method []byte)

SetMethodBytes sets HTTP request method.

func (*RequestHeader) SetMultipartFormBoundary Uses

func (h *RequestHeader) SetMultipartFormBoundary(boundary string)

SetMultipartFormBoundary sets the following Content-Type: 'multipart/form-data; boundary=...' where ... is substituted by the given boundary.

func (*RequestHeader) SetMultipartFormBoundaryBytes Uses

func (h *RequestHeader) SetMultipartFormBoundaryBytes(boundary []byte)

SetMultipartFormBoundaryBytes sets the following Content-Type: 'multipart/form-data; boundary=...' where ... is substituted by the given boundary.

func (*RequestHeader) SetReferer Uses

func (h *RequestHeader) SetReferer(referer string)

SetReferer sets Referer header value.

func (*RequestHeader) SetRefererBytes Uses

func (h *RequestHeader) SetRefererBytes(referer []byte)

SetRefererBytes sets Referer header value.

func (*RequestHeader) SetRequestURI Uses

func (h *RequestHeader) SetRequestURI(requestURI string)

SetRequestURI sets RequestURI for the first HTTP request line. RequestURI must be properly encoded. Use URI.RequestURI for constructing proper RequestURI if unsure.

func (*RequestHeader) SetRequestURIBytes Uses

func (h *RequestHeader) SetRequestURIBytes(requestURI []byte)

SetRequestURIBytes sets RequestURI for the first HTTP request line. RequestURI must be properly encoded. Use URI.RequestURI for constructing proper RequestURI if unsure.

func (*RequestHeader) SetUserAgent Uses

func (h *RequestHeader) SetUserAgent(userAgent string)

SetUserAgent sets User-Agent header value.

func (*RequestHeader) SetUserAgentBytes Uses

func (h *RequestHeader) SetUserAgentBytes(userAgent []byte)

SetUserAgentBytes sets User-Agent header value.

func (*RequestHeader) String Uses

func (h *RequestHeader) String() string

String returns request header representation.

func (*RequestHeader) UserAgent Uses

func (h *RequestHeader) UserAgent() []byte

UserAgent returns User-Agent header value.

func (*RequestHeader) VisitAll Uses

func (h *RequestHeader) VisitAll(f func(key, value []byte))

VisitAll calls f for each header.

f must not retain references to key and/or value after returning. Copy key and/or value contents before returning if you need retaining them.

func (*RequestHeader) VisitAllCookie Uses

func (h *RequestHeader) VisitAllCookie(f func(key, value []byte))

VisitAllCookie calls f for each request cookie.

f must not retain references to key and/or value after returning.

func (*RequestHeader) Write Uses

func (h *RequestHeader) Write(w *bufio.Writer) error

Write writes request header to w.

func (*RequestHeader) WriteTo Uses

func (h *RequestHeader) WriteTo(w io.Writer) (int64, error)

WriteTo writes request header to w.

WriteTo implements io.WriterTo interface.

type Response Uses

type Response struct {

    // Response header
    //
    // Copying Header by value is forbidden. Use pointer to Header instead.
    Header ResponseHeader

    // Response.Read() skips reading body if set to true.
    // Use it for reading HEAD responses.
    //
    // Response.Write() skips writing body if set to true.
    // Use it for writing HEAD responses.
    SkipBody bool
    // contains filtered or unexported fields
}

Response represents HTTP response.

It is forbidden copying Response instances. Create new instances and use CopyTo instead.

Response instance MUST NOT be used from concurrently running goroutines.

func AcquireResponse Uses

func AcquireResponse() *Response

AcquireResponse returns an empty Response instance from response pool.

The returned Response instance may be passed to ReleaseResponse when it is no longer needed. This allows Response recycling, reduces GC pressure and usually improves performance.

func (*Response) AppendBody Uses

func (resp *Response) AppendBody(p []byte)

AppendBody appends p to response body.

It is safe re-using p after the function returns.

func (*Response) AppendBodyString Uses

func (resp *Response) AppendBodyString(s string)

AppendBodyString appends s to response body.

func (*Response) Body Uses

func (resp *Response) Body() []byte

Body returns response body.

func (*Response) BodyGunzip Uses

func (resp *Response) BodyGunzip() ([]byte, error)

BodyGunzip returns un-gzipped body data.

This method may be used if the response header contains 'Content-Encoding: gzip' for reading un-gzipped body. Use Body for reading gzipped response body.

func (*Response) BodyInflate Uses

func (resp *Response) BodyInflate() ([]byte, error)

BodyInflate returns inflated body data.

This method may be used if the response header contains 'Content-Encoding: deflate' for reading inflated response body. Use Body for reading deflated response body.

func (*Response) BodyWriteTo Uses

func (resp *Response) BodyWriteTo(w io.Writer) error

BodyWriteTo writes response body to w.

func (*Response) BodyWriter Uses

func (resp *Response) BodyWriter() io.Writer

BodyWriter returns writer for populating response body.

If used inside RequestHandler, the returned writer must not be used after returning from RequestHandler. Use RequestCtx.Write or SetBodyStreamWriter in this case.

func (*Response) ConnectionClose Uses

func (resp *Response) ConnectionClose() bool

ConnectionClose returns true if 'Connection: close' header is set.

func (*Response) CopyTo Uses

func (resp *Response) CopyTo(dst *Response)

CopyTo copies resp contents to dst except of body stream.

func (*Response) IsBodyStream Uses

func (resp *Response) IsBodyStream() bool

IsBodyStream returns true if body is set via SetBodyStream*

func (*Response) Read Uses

func (resp *Response) Read(r *bufio.Reader) error

Read reads response (including body) from the given r.

io.EOF is returned if r is closed before reading the first header byte.

func (*Response) ReadLimitBody Uses

func (resp *Response) ReadLimitBody(r *bufio.Reader, maxBodySize int) error

ReadLimitBody reads response from the given r, limiting the body size.

If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned.

io.EOF is returned if r is closed before reading the first header byte.

func (*Response) ReleaseBody Uses

func (resp *Response) ReleaseBody(size int)

ReleaseBody retires the response body if it is greater than "size" bytes.

This permits GC to reclaim the large buffer. If used, must be before ReleaseResponse.

Use this method only if you really understand how it works. The majority of workloads don't need this method.

func (*Response) Reset Uses

func (resp *Response) Reset()

Reset clears response contents.

func (*Response) ResetBody Uses

func (resp *Response) ResetBody()

ResetBody resets response body.

func (*Response) SendFile Uses

func (resp *Response) SendFile(path string) error

SendFile registers file on the given path to be used as response body when Write is called.

Note that SendFile doesn't set Content-Type, so set it yourself with Header.SetContentType.

func (*Response) SetBody Uses

func (resp *Response) SetBody(body []byte)

SetBody sets response body.

It is safe re-using body argument after the function returns.

func (*Response) SetBodyStream Uses

func (resp *Response) SetBodyStream(bodyStream io.Reader, bodySize int)

SetBodyStream sets response body stream and, optionally body size.

If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes before returning io.EOF.

If bodySize < 0, then bodyStream is read until io.EOF.

bodyStream.Close() is called after finishing reading all body data if it implements io.Closer.

See also SetBodyStreamWriter.

func (*Response) SetBodyStreamWriter Uses

func (resp *Response) SetBodyStreamWriter(sw StreamWriter)

SetBodyStreamWriter registers the given sw for populating response body.

This function may be used in the following cases:

* if response body is too big (more than 10MB).
* if response body is streamed from slow external sources.
* if response body must be streamed to the client in chunks
(aka `http server push` or `chunked transfer-encoding`).

See also SetBodyStream.

func (*Response) SetBodyString Uses

func (resp *Response) SetBodyString(body string)

SetBodyString sets response body.

func (*Response) SetConnectionClose Uses

func (resp *Response) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*Response) SetStatusCode Uses

func (resp *Response) SetStatusCode(statusCode int)

SetStatusCode sets response status code.

func (*Response) StatusCode Uses

func (resp *Response) StatusCode() int

StatusCode returns response status code.

func (*Response) String Uses

func (resp *Response) String() string

String returns response representation.

Returns error message instead of response representation on error.

Use Write instead of String for performance-critical code.

func (*Response) SwapBody Uses

func (resp *Response) SwapBody(body []byte) []byte

SwapBody swaps response body with the given body and returns the previous response body.

It is forbidden to use the body passed to SwapBody after the function returns.

func (*Response) Write Uses

func (resp *Response) Write(w *bufio.Writer) error

Write writes response to w.

Write doesn't flush response to w for performance reasons.

See also WriteTo.

func (*Response) WriteDeflate Uses

func (resp *Response) WriteDeflate(w *bufio.Writer) error

WriteDeflate writes response with deflated body to w.

The method deflates response body and sets 'Content-Encoding: deflate' header before writing response to w.

WriteDeflate doesn't flush response to w for performance reasons.

func (*Response) WriteDeflateLevel Uses

func (resp *Response) WriteDeflateLevel(w *bufio.Writer, level int) error

WriteDeflateLevel writes response with deflated body to w.

Level is the desired compression level:

* CompressNoCompression
* CompressBestSpeed
* CompressBestCompression
* CompressDefaultCompression

The method deflates response body and sets 'Content-Encoding: deflate' header before writing response to w.

WriteDeflateLevel doesn't flush response to w for performance reasons.

func (*Response) WriteGzip Uses

func (resp *Response) WriteGzip(w *bufio.Writer) error

WriteGzip writes response with gzipped body to w.

The method gzips response body and sets 'Content-Encoding: gzip' header before writing response to w.

WriteGzip doesn't flush response to w for performance reasons.

func (*Response) WriteGzipLevel Uses

func (resp *Response) WriteGzipLevel(w *bufio.Writer, level int) error

WriteGzipLevel writes response with gzipped body to w.

Level is the desired compression level:

* CompressNoCompression
* CompressBestSpeed
* CompressBestCompression
* CompressDefaultCompression

The method gzips response body and sets 'Content-Encoding: gzip' header before writing response to w.

WriteGzipLevel doesn't flush response to w for performance reasons.

func (*Response) WriteTo Uses

func (resp *Response) WriteTo(w io.Writer) (int64, error)

WriteTo writes response to w. It implements io.WriterTo.

type ResponseHeader Uses

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

ResponseHeader represents HTTP response header.

It is forbidden copying ResponseHeader instances. Create new instances instead and use CopyTo.

ResponseHeader instance MUST NOT be used from concurrently running goroutines.

func (*ResponseHeader) Add Uses

func (h *ResponseHeader) Add(key, value string)

Add adds the given 'key: value' header.

Multiple headers with the same key may be added with this function. Use Set for setting a single header for the given key.

func (*ResponseHeader) AddBytesK Uses

func (h *ResponseHeader) AddBytesK(key []byte, value string)

AddBytesK adds the given 'key: value' header.

Multiple headers with the same key may be added with this function. Use SetBytesK for setting a single header for the given key.

func (*ResponseHeader) AddBytesKV Uses

func (h *ResponseHeader) AddBytesKV(key, value []byte)

AddBytesKV adds the given 'key: value' header.

Multiple headers with the same key may be added with this function. Use SetBytesKV for setting a single header for the given key.

func (*ResponseHeader) AddBytesV Uses

func (h *ResponseHeader) AddBytesV(key string, value []byte)

AddBytesV adds the given 'key: value' header.

Multiple headers with the same key may be added with this function. Use SetBytesV for setting a single header for the given key.

func (*ResponseHeader) AppendBytes Uses

func (h *ResponseHeader) AppendBytes(dst []byte) []byte

AppendBytes appends response header representation to dst and returns the extended dst.

func (*ResponseHeader) ConnectionClose Uses

func (h *ResponseHeader) ConnectionClose() bool

ConnectionClose returns true if 'Connection: close' header is set.

func (*ResponseHeader) ConnectionUpgrade Uses

func (h *ResponseHeader) ConnectionUpgrade() bool

ConnectionUpgrade returns true if 'Connection: Upgrade' header is set.

func (*ResponseHeader) ContentLength Uses

func (h *ResponseHeader) ContentLength() int

ContentLength returns Content-Length header value.

It may be negative: -1 means Transfer-Encoding: chunked. -2 means Transfer-Encoding: identity.

func (*ResponseHeader) ContentType Uses

func (h *ResponseHeader) ContentType() []byte

ContentType returns Content-Type header value.

func (*ResponseHeader) Cookie Uses

func (h *ResponseHeader) Cookie(cookie *Cookie) bool

Cookie fills cookie for the given cookie.Key.

Returns false if cookie with the given cookie.Key is missing.

func (*ResponseHeader) CopyTo Uses

func (h *ResponseHeader) CopyTo(dst *ResponseHeader)

CopyTo copies all the headers to dst.

func (*ResponseHeader) Del Uses

func (h *ResponseHeader) Del(key string)

Del deletes header with the given key.

func (*ResponseHeader) DelAllCookies Uses

func (h *ResponseHeader) DelAllCookies()

DelAllCookies removes all the cookies from response headers.

func (*ResponseHeader) DelBytes Uses

func (h *ResponseHeader) DelBytes(key []byte)

DelBytes deletes header with the given key.

func (*ResponseHeader) DelClientCookie Uses

func (h *ResponseHeader) DelClientCookie(key string)

DelClientCookie instructs the client to remove the given cookie.

Use DelCookie if you want just removing the cookie from response header.

func (*ResponseHeader) DelClientCookieBytes Uses

func (h *ResponseHeader) DelClientCookieBytes(key []byte)

DelClientCookieBytes instructs the client to remove the given cookie.

Use DelCookieBytes if you want just removing the cookie from response header.

func (*ResponseHeader) DelCookie Uses

func (h *ResponseHeader) DelCookie(key string)

DelCookie removes cookie under the given key from response header.

Note that DelCookie doesn't remove the cookie from the client. Use DelClientCookie instead.

func (*ResponseHeader) DelCookieBytes Uses

func (h *ResponseHeader) DelCookieBytes(key []byte)

DelCookieBytes removes cookie under the given key from response header.

Note that DelCookieBytes doesn't remove the cookie from the client. Use DelClientCookieBytes instead.

func (*ResponseHeader) DisableNormalizing Uses

func (h *ResponseHeader) DisableNormalizing()

DisableNormalizing disables header names' normalization.

By default all the header names are normalized by uppercasing the first letter and all the first letters following dashes, while lowercasing all the other letters. Examples:

* CONNECTION -> Connection
* conteNT-tYPE -> Content-Type
* foo-bar-baz -> Foo-Bar-Baz

Disable header names' normalization only if know what are you doing.

func (*ResponseHeader) Header Uses

func (h *ResponseHeader) Header() []byte

Header returns response header representation.

The returned value is valid until the next call to ResponseHeader methods.

func (*ResponseHeader) IsHTTP11 Uses

func (h *ResponseHeader) IsHTTP11() bool

IsHTTP11 returns true if the response is HTTP/1.1.

func (*ResponseHeader) Len Uses

func (h *ResponseHeader) Len() int

Len returns the number of headers set, i.e. the number of times f is called in VisitAll.

func (*ResponseHeader) Peek Uses

func (h *ResponseHeader) Peek(key string) []byte

Peek returns header value for the given key.

Returned value is valid until the next call to ResponseHeader. Do not store references to returned value. Make copies instead.

func (*ResponseHeader) PeekBytes Uses

func (h *ResponseHeader) PeekBytes(key []byte) []byte

PeekBytes returns header value for the given key.

Returned value is valid until the next call to ResponseHeader. Do not store references to returned value. Make copies instead.

func (*ResponseHeader) Read Uses

func (h *ResponseHeader) Read(r *bufio.Reader) error

Read reads response header from r.

io.EOF is returned if r is closed before reading the first header byte.

func (*ResponseHeader) Reset Uses

func (h *ResponseHeader) Reset()

Reset clears response header.

func (*ResponseHeader) ResetConnectionClose Uses

func (h *ResponseHeader) ResetConnectionClose()

ResetConnectionClose clears 'Connection: close' header if it exists.

func (*ResponseHeader) Server Uses

func (h *ResponseHeader) Server() []byte

Server returns Server header value.

func (*ResponseHeader) Set Uses

func (h *ResponseHeader) Set(key, value string)

Set sets the given 'key: value' header.

Use Add for setting multiple header values under the same key.

func (*ResponseHeader) SetBytesK Uses

func (h *ResponseHeader) SetBytesK(key []byte, value string)

SetBytesK sets the given 'key: value' header.

Use AddBytesK for setting multiple header values under the same key.

func (*ResponseHeader) SetBytesKV Uses

func (h *ResponseHeader) SetBytesKV(key, value []byte)

SetBytesKV sets the given 'key: value' header.

Use AddBytesKV for setting multiple header values under the same key.

func (*ResponseHeader) SetBytesV Uses

func (h *ResponseHeader) SetBytesV(key string, value []byte)

SetBytesV sets the given 'key: value' header.

Use AddBytesV for setting multiple header values under the same key.

func (*ResponseHeader) SetCanonical Uses

func (h *ResponseHeader) SetCanonical(key, value []byte)

SetCanonical sets the given 'key: value' header assuming that key is in canonical form.

func (*ResponseHeader) SetConnectionClose Uses

func (h *ResponseHeader) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*ResponseHeader) SetContentLength Uses

func (h *ResponseHeader) SetContentLength(contentLength int)

SetContentLength sets Content-Length header value.

Content-Length may be negative: -1 means Transfer-Encoding: chunked. -2 means Transfer-Encoding: identity.

func (*ResponseHeader) SetContentRange Uses

func (h *ResponseHeader) SetContentRange(startPos, endPos, contentLength int)

SetContentRange sets 'Content-Range: bytes startPos-endPos/contentLength' header.

func (*ResponseHeader) SetContentType Uses

func (h *ResponseHeader) SetContentType(contentType string)

SetContentType sets Content-Type header value.

func (*ResponseHeader) SetContentTypeBytes Uses

func (h *ResponseHeader) SetContentTypeBytes(contentType []byte)

SetContentTypeBytes sets Content-Type header value.

func (*ResponseHeader) SetCookie Uses

func (h *ResponseHeader) SetCookie(cookie *Cookie)

SetCookie sets the given response cookie.

It is save re-using the cookie after the function returns.

func (*ResponseHeader) SetLastModified Uses

func (h *ResponseHeader) SetLastModified(t time.Time)

SetLastModified sets 'Last-Modified' header to the given value.

func (*ResponseHeader) SetServer Uses

func (h *ResponseHeader) SetServer(server string)

SetServer sets Server header value.

func (*ResponseHeader) SetServerBytes Uses

func (h *ResponseHeader) SetServerBytes(server []byte)

SetServerBytes sets Server header value.

func (*ResponseHeader) SetStatusCode Uses

func (h *ResponseHeader) SetStatusCode(statusCode int)

SetStatusCode sets response status code.

func (*ResponseHeader) StatusCode Uses

func (h *ResponseHeader) StatusCode() int

StatusCode returns response status code.

func (*ResponseHeader) String Uses

func (h *ResponseHeader) String() string

String returns response header representation.

func (*ResponseHeader) VisitAll Uses

func (h *ResponseHeader) VisitAll(f func(key, value []byte))

VisitAll calls f for each header.

f must not retain references to key and/or value after returning. Copy key and/or value contents before returning if you need retaining them.

func (*ResponseHeader) VisitAllCookie Uses

func (h *ResponseHeader) VisitAllCookie(f func(key, value []byte))

VisitAllCookie calls f for each response cookie.

Cookie name is passed in key and the whole Set-Cookie header value is passed in value on each f invocation. Value may be parsed with Cookie.ParseBytes().

f must not retain references to key and/or value after returning.

func (*ResponseHeader) Write Uses

func (h *ResponseHeader) Write(w *bufio.Writer) error

Write writes response header to w.

func (*ResponseHeader) WriteTo Uses

func (h *ResponseHeader) WriteTo(w io.Writer) (int64, error)

WriteTo writes response header to w.

WriteTo implements io.WriterTo interface.

type Server Uses

type Server struct {

    // Handler for processing incoming requests.
    Handler RequestHandler

    // Server name for sending in response headers.
    //
    // Default server name is used if left blank.
    Name string

    // The maximum number of concurrent connections the server may serve.
    //
    // DefaultConcurrency is used if not set.
    Concurrency int

    // Whether to disable keep-alive connections.
    //
    // The server will close all the incoming connections after sending
    // the first response to client if this option is set to true.
    //
    // By default keep-alive connections are enabled.
    DisableKeepalive bool

    // Per-connection buffer size for requests' reading.
    // This also limits the maximum header size.
    //
    // Increase this buffer if your clients send multi-KB RequestURIs
    // and/or multi-KB headers (for example, BIG cookies).
    //
    // Default buffer size is used if not set.
    ReadBufferSize int

    // Per-connection buffer size for responses' writing.
    //
    // Default buffer size is used if not set.
    WriteBufferSize int

    // Maximum duration for reading the full request (including body).
    //
    // This also limits the maximum duration for idle keep-alive
    // connections.
    //
    // By default request read timeout is unlimited.
    ReadTimeout time.Duration

    // Maximum duration for writing the full response (including body).
    //
    // By default response write timeout is unlimited.
    WriteTimeout time.Duration

    // Maximum number of concurrent client connections allowed per IP.
    //
    // By default unlimited number of concurrent connections
    // may be established to the server from a single IP address.
    MaxConnsPerIP int

    // Maximum number of requests served per connection.
    //
    // The server closes connection after the last request.
    // 'Connection: close' header is added to the last response.
    //
    // By default unlimited number of requests may be served per connection.
    MaxRequestsPerConn int

    // Maximum keep-alive connection lifetime.
    //
    // The server closes keep-alive connection after its' lifetime
    // expiration.
    //
    // See also ReadTimeout for limiting the duration of idle keep-alive
    // connections.
    //
    // By default keep-alive connection lifetime is unlimited.
    MaxKeepaliveDuration time.Duration

    // Maximum request body size.
    //
    // The server rejects requests with bodies exceeding this limit.
    //
    // Request body size is limited by DefaultMaxRequestBodySize by default.
    MaxRequestBodySize int

    // Aggressively reduces memory usage at the cost of higher CPU usage
    // if set to true.
    //
    // Try enabling this option only if the server consumes too much memory
    // serving mostly idle keep-alive connections. This may reduce memory
    // usage by more than 50%.
    //
    // Aggressive memory usage reduction is disabled by default.
    ReduceMemoryUsage bool

    // Rejects all non-GET requests if set to true.
    //
    // This option is useful as anti-DoS protection for servers
    // accepting only GET requests. The request size is limited
    // by ReadBufferSize if GetOnly is set.
    //
    // Server accepts all the requests by default.
    GetOnly bool

    // Logs all errors, including the most frequent
    // 'connection reset by peer', 'broken pipe' and 'connection timeout'
    // errors. Such errors are common in production serving real-world
    // clients.
    //
    // By default the most frequent errors such as
    // 'connection reset by peer', 'broken pipe' and 'connection timeout'
    // are suppressed in order to limit output log traffic.
    LogAllErrors bool

    // Header names are passed as-is without normalization
    // if this option is set.
    //
    // Disabled header names' normalization may be useful only for proxying
    // incoming requests to other servers expecting case-sensitive
    // header names. See https://github.com/valyala/fasthttp/issues/57
    // for details.
    //
    // By default request and response header names are normalized, i.e.
    // The first letter and the first letters following dashes
    // are uppercased, while all the other letters are lowercased.
    // Examples:
    //
    //     * HOST -> Host
    //     * content-type -> Content-Type
    //     * cONTENT-lenGTH -> Content-Length
    DisableHeaderNamesNormalizing bool

    // Logger, which is used by RequestCtx.Logger().
    //
    // By default standard logger from log package is used.
    Logger Logger
    // contains filtered or unexported fields
}

Server implements HTTP server.

Default Server settings should satisfy the majority of Server users. Adjust Server settings only if you really understand the consequences.

It is forbidden copying Server instances. Create new Server instances instead.

It is safe to call Server methods from concurrently running goroutines.

Code:

// This function will be called by the server for each incoming request.
//
// RequestCtx provides a lot of functionality related to http request
// processing. See RequestCtx docs for details.
requestHandler := func(ctx *fasthttp.RequestCtx) {
    fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path())
}

// Create custom server.
s := &fasthttp.Server{
    Handler: requestHandler,

    // Every response will contain 'Server: My super server' header.
    Name: "My super server",

    // Other Server settings may be set here.
}

// Start the server listening for incoming requests on the given address.
//
// ListenAndServe returns only on error, so usually it blocks forever.
if err := s.ListenAndServe("127.0.0.1:80"); err != nil {
    log.Fatalf("error in ListenAndServe: %s", err)
}

func (*Server) ListenAndServe Uses

func (s *Server) ListenAndServe(addr string) error

ListenAndServe serves HTTP requests from the given TCP4 addr.

Pass custom listener to Serve if you need listening on non-TCP4 media such as IPv6.

func (*Server) ListenAndServeTLS Uses

func (s *Server) ListenAndServeTLS(addr, certFile, keyFile string) error

ListenAndServeTLS serves HTTPS requests from the given TCP4 addr.

certFile and keyFile are paths to TLS certificate and key files.

Pass custom listener to Serve if you need listening on non-TCP4 media such as IPv6.

func (*Server) ListenAndServeTLSEmbed Uses

func (s *Server) ListenAndServeTLSEmbed(addr string, certData, keyData []byte) error

ListenAndServeTLSEmbed serves HTTPS requests from the given TCP4 addr.

certData and keyData must contain valid TLS certificate and key data.

Pass custom listener to Serve if you need listening on arbitrary media such as IPv6.

func (*Server) ListenAndServeUNIX Uses

func (s *Server) ListenAndServeUNIX(addr string, mode os.FileMode) error

ListenAndServeUNIX serves HTTP requests from the given UNIX addr.

The function deletes existing file at addr before starting serving.

The server sets the given file mode for the UNIX addr.

func (*Server) Serve Uses

func (s *Server) Serve(ln net.Listener) error

Serve serves incoming connections from the given listener.

Serve blocks until the given listener returns permanent error.

func (*Server) ServeConn Uses

func (s *Server) ServeConn(c net.Conn) error

ServeConn serves HTTP requests from the given connection.

ServeConn returns nil if all requests from the c are successfully served. It returns non-nil error otherwise.

Connection c must immediately propagate all the data passed to Write() to the client. Otherwise requests' processing may hang.

ServeConn closes c before returning.

func (*Server) ServeTLS Uses

func (s *Server) ServeTLS(ln net.Listener, certFile, keyFile string) error

ServeTLS serves HTTPS requests from the given listener.

certFile and keyFile are paths to TLS certificate and key files.

func (*Server) ServeTLSEmbed Uses

func (s *Server) ServeTLSEmbed(ln net.Listener, certData, keyData []byte) error

ServeTLSEmbed serves HTTPS requests from the given listener.

certData and keyData must contain valid TLS certificate and key data.

type StreamWriter Uses

type StreamWriter func(w *bufio.Writer)

StreamWriter must write data to w.

Usually StreamWriter writes data to w in a loop (aka 'data streaming').

StreamWriter must return immediately if w returns error.

Since the written data is buffered, do not forget calling w.Flush when the data must be propagated to reader.

type URI Uses

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

URI represents URI :) .

It is forbidden copying URI instances. Create new instance and use CopyTo instead.

URI instance MUST NOT be used from concurrently running goroutines.

func AcquireURI Uses

func AcquireURI() *URI

AcquireURI returns an empty URI instance from the pool.

Release the URI with ReleaseURI after the URI is no longer needed. This allows reducing GC load.

func (*URI) AppendBytes Uses

func (u *URI) AppendBytes(dst []byte) []byte

AppendBytes appends full uri to dst and returns the extended dst.

func (*URI) CopyTo Uses

func (u *URI) CopyTo(dst *URI)

CopyTo copies uri contents to dst.

func (*URI) FullURI Uses

func (u *URI) FullURI() []byte

FullURI returns full uri in the form {Scheme}://{Host}{RequestURI}#{Hash}.

func (*URI) Hash Uses

func (u *URI) Hash() []byte

Hash returns URI hash, i.e. qwe of http://aaa.com/foo/bar?baz=123#qwe .

The returned value is valid until the next URI method call.

func (*URI) Host Uses

func (u *URI) Host() []byte

Host returns host part, i.e. aaa.com of http://aaa.com/foo/bar?baz=123#qwe .

Host is always lowercased.

func (*URI) LastPathSegment Uses

func (u *URI) LastPathSegment() []byte

LastPathSegment returns the last part of uri path after '/'.

Examples:

* For /foo/bar/baz.html path returns baz.html.
* For /foo/bar/ returns empty byte slice.
* For /foobar.js returns foobar.js.

func (*URI) Parse Uses

func (u *URI) Parse(host, uri []byte)

Parse initializes URI from the given host and uri.

host may be nil. In this case uri must contain fully qualified uri, i.e. with scheme and host. http is assumed if scheme is omitted.

uri may contain e.g. RequestURI without scheme and host if host is non-empty.

func (*URI) Path Uses

func (u *URI) Path() []byte

Path returns URI path, i.e. /foo/bar of http://aaa.com/foo/bar?baz=123#qwe .

The returned path is always urldecoded and normalized, i.e. '//f%20obar/baz/../zzz' becomes '/f obar/zzz'.

The returned value is valid until the next URI method call.

func (*URI) PathOriginal Uses

func (u *URI) PathOriginal() []byte

PathOriginal returns the original path from requestURI passed to URI.Parse().

The returned value is valid until the next URI method call.

func (*URI) QueryArgs Uses

func (u *URI) QueryArgs() *Args

QueryArgs returns query args.

func (*URI) QueryString Uses

func (u *URI) QueryString() []byte

QueryString returns URI query string, i.e. baz=123 of http://aaa.com/foo/bar?baz=123#qwe .

The returned value is valid until the next URI method call.

func (*URI) RequestURI Uses

func (u *URI) RequestURI() []byte

RequestURI returns RequestURI - i.e. URI without Scheme and Host.

func (*URI) Reset Uses

func (u *URI) Reset()

Reset clears uri.

func (*URI) Scheme Uses

func (u *URI) Scheme() []byte

Scheme returns URI scheme, i.e. http of http://aaa.com/foo/bar?baz=123#qwe .

Returned scheme is always lowercased.

The returned value is valid until the next URI method call.

func (*URI) SetHash Uses

func (u *URI) SetHash(hash string)

SetHash sets URI hash.

func (*URI) SetHashBytes Uses

func (u *URI) SetHashBytes(hash []byte)

SetHashBytes sets URI hash.

func (*URI) SetHost Uses

func (u *URI) SetHost(host string)

SetHost sets host for the uri.

func (*URI) SetHostBytes Uses

func (u *URI) SetHostBytes(host []byte)

SetHostBytes sets host for the uri.

func (*URI) SetPath Uses

func (u *URI) SetPath(path string)

SetPath sets URI path.

func (*URI) SetPathBytes Uses

func (u *URI) SetPathBytes(path []byte)

SetPathBytes sets URI path.

func (*URI) SetQueryString Uses

func (u *URI) SetQueryString(queryString string)

SetQueryString sets URI query string.

func (*URI) SetQueryStringBytes Uses

func (u *URI) SetQueryStringBytes(queryString []byte)

SetQueryStringBytes sets URI query string.

func (*URI) SetScheme Uses

func (u *URI) SetScheme(scheme string)

SetScheme sets URI scheme, i.e. http, https, ftp, etc.

func (*URI) SetSchemeBytes Uses

func (u *URI) SetSchemeBytes(scheme []byte)

SetSchemeBytes sets URI scheme, i.e. http, https, ftp, etc.

func (*URI) String Uses

func (u *URI) String() string

String returns full uri.

func (*URI) Update Uses

func (u *URI) Update(newURI string)

Update updates uri.

The following newURI types are accepted:

* Absolute, i.e. http://foobar.com/aaa/bb?cc . In this case the original
  uri is replaced by newURI.
* Absolute without scheme, i.e. //foobar.com/aaa/bb?cc. In this case
  the original scheme is preserved.
* Missing host, i.e. /aaa/bb?cc . In this case only RequestURI part
  of the original uri is replaced.
* Relative path, i.e.  xx?yy=abc . In this case the original RequestURI
  is updated according to the new relative path.

func (*URI) UpdateBytes Uses

func (u *URI) UpdateBytes(newURI []byte)

UpdateBytes updates uri.

The following newURI types are accepted:

* Absolute, i.e. http://foobar.com/aaa/bb?cc . In this case the original
  uri is replaced by newURI.
* Absolute without scheme, i.e. //foobar.com/aaa/bb?cc. In this case
  the original scheme is preserved.
* Missing host, i.e. /aaa/bb?cc . In this case only RequestURI part
  of the original uri is replaced.
* Relative path, i.e.  xx?yy=abc . In this case the original RequestURI
  is updated according to the new relative path.

func (*URI) WriteTo Uses

func (u *URI) WriteTo(w io.Writer) (int64, error)

WriteTo writes full uri to w.

WriteTo implements io.WriterTo interface.

Directories

PathSynopsis
expvarhandlerPackage expvarhandler provides fasthttp-compatible request handler serving expvars.
fasthttpadaptorPackage fasthttpadaptor provides helper functions for converting net/http request handlers to fasthttp request handlers.
fasthttputilPackage fasthttputil provides utility functions for fasthttp.
reuseportPackage reuseport provides TCP net.Listener with SO_REUSEPORT support.
stacklessPackage stackless provides functionality that may save stack space for high number of concurrently running goroutines.

Package fasthttp imports 31 packages (graph) and is imported by 185 packages. Updated 2017-02-22. Refresh now. Tools for package owners.