hx

package module
v0.0.0-unstable.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2021 License: MIT Imports: 20 Imported by: 0

README

hx experimental

Work in progress.

Simplified and reworked fork of fasthttp.

Intended to serve plaintext HTTP 1.1 behind load balancer and reverse-pory in controlled environment.

Fully buffer request or response.

Non-goals

  • Client
  • Load balancing
  • WebSocket
  • Streaming, like io.Reader or io.Writer
  • Forms
  • File
  • HTTP 2.0, 3.0, QUIC
  • TLS
  • Running without reverse proxy

Documentation

Overview

Package hx provides fast HTTP server 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.
  • 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.

Index

Examples

Constants

View Source
const (
	// Authentication
	HeaderAuthorization      = "Authorization"
	HeaderProxyAuthenticate  = "Proxy-Authenticate"
	HeaderProxyAuthorization = "Proxy-Authorization"
	HeaderWWWAuthenticate    = "WWW-Authenticate"

	// Caching
	HeaderAge           = "Age"
	HeaderCacheControl  = "Cache-Control"
	HeaderClearSiteData = "Clear-Site-Data"
	HeaderExpires       = "Expires"
	HeaderPragma        = "Pragma"
	HeaderWarning       = "Warning"

	// Client hints
	HeaderAcceptCH         = "Accept-CH"
	HeaderAcceptCHLifetime = "Accept-CH-Lifetime"
	HeaderContentDPR       = "Content-DPR"
	HeaderDPR              = "DPR"
	HeaderEarlyData        = "Early-Data"
	HeaderSaveData         = "Save-Data"
	HeaderViewportWidth    = "Viewport-Width"
	HeaderWidth            = "Width"

	// Conditionals
	HeaderETag              = "ETag"
	HeaderIfMatch           = "If-Match"
	HeaderIfModifiedSince   = "If-Modified-Since"
	HeaderIfNoneMatch       = "If-None-Match"
	HeaderIfUnmodifiedSince = "If-Unmodified-Since"
	HeaderLastModified      = "Last-Modified"
	HeaderVary              = "Vary"

	// Connection management
	HeaderConnection = "Connection"
	HeaderKeepAlive  = "Keep-Alive"

	// Content negotiation
	HeaderAccept         = "Accept"
	HeaderAcceptCharset  = "Accept-Charset"
	HeaderAcceptEncoding = "Accept-Encoding"
	HeaderAcceptLanguage = "Accept-Language"

	// Controls
	HeaderCookie      = "Cookie"
	HeaderExpect      = "Expect"
	HeaderMaxForwards = "Max-Forwards"
	HeaderSetCookie   = "Set-Cookie"

	// CORS
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderOrigin                        = "Origin"
	HeaderTimingAllowOrigin             = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies"

	// Do Not Track
	HeaderDNT = "DNT"
	HeaderTk  = "Tk"

	// Downloads
	HeaderContentDisposition = "Content-Disposition"

	// Message body information
	HeaderContentEncoding = "Content-Encoding"
	HeaderContentLanguage = "Content-Language"
	HeaderContentLength   = "Content-Length"
	HeaderContentLocation = "Content-Location"
	HeaderContentType     = "Content-Type"

	// Proxies
	HeaderForwarded       = "Forwarded"
	HeaderVia             = "Via"
	HeaderXForwardedFor   = "X-Forwarded-For"
	HeaderXForwardedHost  = "X-Forwarded-Host"
	HeaderXForwardedProto = "X-Forwarded-Proto"

	// Redirects
	HeaderLocation = "Location"

	// Request context
	HeaderFrom           = "From"
	HeaderHost           = "Host"
	HeaderReferer        = "Referer"
	HeaderReferrerPolicy = "Referrer-Policy"
	HeaderUserAgent      = "User-Agent"

	// Response context
	HeaderAllow  = "Allow"
	HeaderServer = "Server"

	// Range requests
	HeaderAcceptRanges = "Accept-Ranges"
	HeaderContentRange = "Content-Range"
	HeaderIfRange      = "If-Range"
	HeaderRange        = "Range"

	// Security
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy       = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                        = "Expect-CT"
	HeaderFeaturePolicy                   = "Feature-Policy"
	HeaderPublicKeyPins                   = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXDownloadOptions                = "X-Download-Options"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXPoweredBy                      = "X-Powered-By"
	HeaderXXSSProtection                  = "X-XSS-Protection"

	// Server-sent event
	HeaderLastEventID = "Last-Event-ID"
	HeaderNEL         = "NEL"
	HeaderPingFrom    = "Ping-From"
	HeaderPingTo      = "Ping-To"
	HeaderReportTo    = "Report-To"

	// Transfer coding
	HeaderTE               = "TE"
	HeaderTrailer          = "Trailer"
	HeaderTransferEncoding = "Transfer-Encoding"

	// WebSockets
	HeaderSecWebSocketAccept     = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey        = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol   = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion    = "Sec-WebSocket-Version"

	// Other
	HeaderAcceptPatch         = "Accept-Patch"
	HeaderAcceptPushPolicy    = "Accept-Push-Policy"
	HeaderAcceptSignature     = "Accept-Signature"
	HeaderAltSvc              = "Alt-Svc"
	HeaderDate                = "Date"
	HeaderIndex               = "Index"
	HeaderLargeAllocation     = "Large-Allocation"
	HeaderLink                = "Link"
	HeaderPushPolicy          = "Push-Policy"
	HeaderRetryAfter          = "Retry-After"
	HeaderServerTiming        = "Server-Timing"
	HeaderSignature           = "Signature"
	HeaderSignedHeaders       = "Signed-Headers"
	HeaderSourceMap           = "SourceMap"
	HeaderUpgrade             = "Upgrade"
	HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control"
	HeaderXPingback           = "X-Pingback"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderXRobotsTag          = "X-Robots-Tag"
	HeaderXUACompatible       = "X-UA-Compatible"
)

Headers

View Source
const (
	MethodGet     = "GET"     // RFC 7231, 4.3.1
	MethodHead    = "HEAD"    // RFC 7231, 4.3.2
	MethodPost    = "POST"    // RFC 7231, 4.3.3
	MethodPut     = "PUT"     // RFC 7231, 4.3.4
	MethodPatch   = "PATCH"   // RFC 5789
	MethodDelete  = "DELETE"  // RFC 7231, 4.3.5
	MethodConnect = "CONNECT" // RFC 7231, 4.3.6
	MethodOptions = "OPTIONS" // RFC 7231, 4.3.7
	MethodTrace   = "TRACE"   // RFC 7231, 4.3.8
)

HTTP methods were copied from net/http.

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

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

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

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

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest           = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	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.

View Source
const DefaultWorkers = 100

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

View Source
const Race = false

Race reports if the race detector is enabled.

Variables

View Source
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
)
View Source
var ErrBodyTooLarge = errors.New("body size exceeds the given limit")

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

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

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

View Source
var ErrTimeout = errors.New("timeout")
View Source
var (
	ErrorInvalidURI = errors.New("invalid uri")
)

Functions

func AppendHTMLEscape

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

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

func AppendHTMLEscapeBytes

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

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

func AppendHTTPDate

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

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

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

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

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

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

func AppendUint

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

AppendUint appends n to dst and returns the extended dst.

func AppendUnquotedArg

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

AppendUnquotedArg appends url-decoded src to dst and returns appended dst.

dst may point to src. In this case src will be overwritten.

func ListenAndServe

func ListenAndServe(addr string, handler Handler) error

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

Example
package main

import (
	"fmt"
	"log"

	"github.com/go-faster/hx"
)

func main() {
	// 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.
	//
	// Ctx provides a lot of functionality related to http request
	// processing. See Ctx docs for details.
	requestHandler := func(ctx *hx.Ctx) {
		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 := hx.ListenAndServe(listenAddr, requestHandler); err != nil {
		log.Fatalf("error in ListenAndServe: %s", err)
	}
}
Output:

func ParseHTTPDate

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

ParseHTTPDate parses HTTP-compliant (RFC1123) date.

func ParseIPv4

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

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

ParseUfloat parses unsigned float from buf.

func ParseUint

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

ParseUint parses uint from buf.

func ReleaseArgs

func ReleaseArgs(a *Args)

ReleaseArgs returns the object acquired via AcquireArgs to the pool.

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

func ReleaseCookie

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 ReleaseURI

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 Serve

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

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

Serve blocks until the given listener returns permanent error.

Example
package main

import (
	"fmt"
	"log"
	"net"

	"github.com/go-faster/hx"
)

func main() {
	// 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.
	//
	// Ctx provides a lot of functionality related to http request
	// processing. See Ctx docs for details.
	requestHandler := func(ctx *hx.Ctx) {
		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 := hx.Serve(ln, requestHandler); err != nil {
		log.Fatalf("error in Serve: %s", err)
	}
}
Output:

func ServeConn

func ServeConn(c net.Conn, handler Handler) 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 StatusMessage

func StatusMessage(statusCode int) string

StatusMessage returns HTTP status message for the given status code.

Types

type Args

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

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

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

Add adds 'key=value' argument.

Multiple values for the same key may be added.

func (*Args) AddBytesK

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

AddBytesK adds 'key=value' argument.

Multiple values for the same key may be added.

func (*Args) AddBytesKNoValue

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

AddBytesKNoValue adds only 'key' as argument without the '='.

Multiple values for the same key may be added.

func (*Args) AddBytesKV

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

AddBytesKV adds 'key=value' argument.

Multiple values for the same key may be added.

func (*Args) AddBytesV

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

AddBytesV adds 'key=value' argument.

Multiple values for the same key may be added.

func (*Args) AddNoValue

func (a *Args) AddNoValue(key string)

AddNoValue adds only 'key' as argument without the '='.

Multiple values for the same key may be added.

func (*Args) AppendBytes

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

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

func (*Args) CopyTo

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

CopyTo copies all args to dst.

func (*Args) Del

func (a *Args) Del(key string)

Del deletes argument with the given key from query args.

func (*Args) DelBytes

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

DelBytes deletes argument with the given key from query args.

func (*Args) GetBool

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

GetBool returns boolean value for the given key.

true is returned for "1", "t", "T", "true", "TRUE", "True", "y", "yes", "Y", "YES", "Yes", otherwise false is returned.

func (*Args) GetUfloat

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

GetUfloat returns ufloat value for the given key.

func (*Args) GetUfloatOrZero

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

GetUfloatOrZero returns ufloat value for the given key.

Zero (0) is returned on error.

func (*Args) GetUint

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

GetUint returns uint value for the given key.

func (*Args) GetUintOrZero

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

GetUintOrZero returns uint value for the given key.

Zero (0) is returned on error.

func (*Args) Has

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

Has returns true if the given key exists in Args.

func (*Args) HasBytes

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

HasBytes returns true if the given key exists in Args.

func (*Args) Len

func (a *Args) Len() int

Len returns the number of query args.

func (*Args) Parse

func (a *Args) Parse(s string)

Parse parses the given string containing query args.

func (*Args) ParseBytes

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

ParseBytes parses the given b containing query args.

func (*Args) Peek

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

Peek returns query arg value for the given key.

The returned value is valid until the Args is reused or released (ReleaseArgs). Do not store references to the returned value. Make copies instead.

func (*Args) PeekBytes

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

PeekBytes returns query arg value for the given key.

The returned value is valid until the Args is reused or released (ReleaseArgs). Do not store references to the returned value. Make copies instead.

func (*Args) PeekMulti

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

PeekMulti returns all the arg values for the given key.

func (*Args) PeekMultiBytes

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

PeekMultiBytes returns all the arg values for the given key.

func (*Args) QueryString

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

QueryString returns query string for the args.

The returned value is valid until the Args is reused or released (ReleaseArgs). Do not store references to the returned value. Make copies instead.

func (*Args) Reset

func (a *Args) Reset()

Reset clears query args.

func (*Args) Set

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

Set sets 'key=value' argument.

func (*Args) SetBytesK

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

SetBytesK sets 'key=value' argument.

func (*Args) SetBytesKNoValue

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

SetBytesKNoValue sets 'key' argument.

func (*Args) SetBytesKV

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

SetBytesKV sets 'key=value' argument.

func (*Args) SetBytesV

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

SetBytesV sets 'key=value' argument.

func (*Args) SetNoValue

func (a *Args) SetNoValue(key string)

SetNoValue sets only 'key' as argument without the '='.

Only key in argumemt, like key1&key2

func (*Args) SetUint

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

SetUint sets uint value for the given key.

func (*Args) SetUintBytes

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

SetUintBytes sets uint value for the given key.

func (*Args) Sort

func (a *Args) Sort(f func(x, y []byte) int)

Sort sorts Args by key and then value using 'f' as comparison function.

For example args.Sort(bytes.Compare)

func (*Args) String

func (a *Args) String() string

String returns string representation of query args.

func (*Args) VisitAll

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

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

WriteTo writes query string to w.

WriteTo implements io.WriterTo interface.

type Buffer

type Buffer struct {
	Buf []byte
}

Buffer is bytes.Buffer.

func (*Buffer) Copy

func (b *Buffer) Copy() []byte

Copy returns new copy of buffer.

func (*Buffer) Expand

func (b *Buffer) Expand(n int)

Expand expands buffer to add n bytes.

func (Buffer) Len

func (b Buffer) Len() int

Len returns length of internal buffer.

func (*Buffer) Put

func (b *Buffer) Put(raw []byte)

Put appends raw bytes to buffer.

Buffer does not retain raw.

func (*Buffer) PutString

func (b *Buffer) PutString(s string)

func (*Buffer) Read

func (b *Buffer) Read(p []byte) (n int, err error)

Read implements io.Reader.

func (*Buffer) Reset

func (b *Buffer) Reset()

func (*Buffer) ResetN

func (b *Buffer) ResetN(n int)

ResetN resets buffer and expands it to fit n bytes.

func (*Buffer) ResetTo

func (b *Buffer) ResetTo(buf []byte)

ResetTo sets internal buffer exactly to provided value.

Buffer will retain buf, so user should not modify or read it concurrently.

func (*Buffer) Skip

func (b *Buffer) Skip(n int)

Skip moves cursor for next n bytes.

func (*Buffer) String

func (b *Buffer) String() string

func (*Buffer) Write

func (b *Buffer) Write(buf []byte) (int, error)

type ConnState

type ConnState int

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

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

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

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

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

func (ConnState) String

func (c ConnState) String() string
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

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

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

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

func (*Cookie) Cookie

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

Cookie returns cookie representation.

The returned value is valid until the Cookie reused or released (ReleaseCookie). Do not store references to the returned value. Make copies instead.

func (*Cookie) CopyTo

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

CopyTo copies src cookie to c.

func (*Cookie) Domain

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

Domain returns cookie domain.

The returned value is valid until the Cookie reused or released (ReleaseCookie). Do not store references to the returned value. Make copies instead.

func (*Cookie) Expire

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

Expire returns cookie expiration time.

CookieExpireUnlimited is returned if cookie doesn't expire

func (*Cookie) HTTPOnly

func (c *Cookie) HTTPOnly() bool

HTTPOnly returns true if the cookie is http only.

func (*Cookie) Key

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

Key returns cookie name.

The returned value is valid until the Cookie reused or released (ReleaseCookie). Do not store references to the returned value. Make copies instead.

func (*Cookie) MaxAge

func (c *Cookie) MaxAge() int

MaxAge returns the seconds until the cookie is meant to expire or 0 if no max age.

func (*Cookie) Parse

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

Parse parses Set-Cookie header.

func (*Cookie) ParseBytes

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

ParseBytes parses Set-Cookie header.

func (*Cookie) Path

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

Path returns cookie path.

func (*Cookie) Reset

func (c *Cookie) Reset()

Reset clears the cookie.

func (*Cookie) SameSite

func (c *Cookie) SameSite() CookieSameSite

SameSite returns the SameSite mode.

func (*Cookie) Secure

func (c *Cookie) Secure() bool

Secure returns true if the cookie is secure.

func (*Cookie) SetDomain

func (c *Cookie) SetDomain(domain string)

SetDomain sets cookie domain.

func (*Cookie) SetDomainBytes

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

SetDomainBytes sets cookie domain.

func (*Cookie) SetExpire

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

func (c *Cookie) SetHTTPOnly(httpOnly bool)

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

func (*Cookie) SetKey

func (c *Cookie) SetKey(key string)

SetKey sets cookie name.

func (*Cookie) SetKeyBytes

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

SetKeyBytes sets cookie name.

func (*Cookie) SetMaxAge

func (c *Cookie) SetMaxAge(seconds int)

SetMaxAge sets cookie expiration time based on seconds. This takes precedence over any absolute expiry set on the cookie

Set max age to 0 to unset

func (*Cookie) SetPath

func (c *Cookie) SetPath(path string)

SetPath sets cookie path.

func (*Cookie) SetPathBytes

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

SetPathBytes sets cookie path.

func (*Cookie) SetSameSite

func (c *Cookie) SetSameSite(mode CookieSameSite)

SetSameSite sets the cookie's SameSite flag to the given value. set value CookieSameSiteNoneMode will set Secure to true also to avoid browser rejection

func (*Cookie) SetSecure

func (c *Cookie) SetSecure(secure bool)

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

func (*Cookie) SetValue

func (c *Cookie) SetValue(value string)

SetValue sets cookie value.

func (*Cookie) SetValueBytes

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

SetValueBytes sets cookie value.

func (*Cookie) String

func (c *Cookie) String() string

String returns cookie representation.

func (*Cookie) Value

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

Value returns cookie value.

The returned value is valid until the Cookie reused or released (ReleaseCookie). Do not store references to the returned value. Make copies instead.

func (*Cookie) WriteTo

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

WriteTo writes cookie representation to w.

WriteTo implements io.WriterTo interface.

type CookieSameSite

type CookieSameSite int

CookieSameSite is an enum for the mode in which the SameSite flag should be set for the given cookie. See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.

const (
	// CookieSameSiteDisabled removes the SameSite flag
	CookieSameSiteDisabled CookieSameSite = iota
	// CookieSameSiteDefaultMode sets the SameSite flag
	CookieSameSiteDefaultMode
	// CookieSameSiteLaxMode sets the SameSite flag with the "Lax" parameter
	CookieSameSiteLaxMode
	// CookieSameSiteStrictMode sets the SameSite flag with the "Strict" parameter
	CookieSameSiteStrictMode
	// CookieSameSiteNoneMode sets the SameSite flag with the "None" parameter
	// see https://tools.ietf.org/html/draft-west-cookie-incrementalism-00
	CookieSameSiteNoneMode
)

type Ctx

type Ctx 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
}

Ctx contains incoming request and manages outgoing response.

It is forbidden to copy Ctx instances.

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

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

func (*Ctx) Conn

func (c *Ctx) Conn() net.Conn

Conn returns a reference to the underlying net.Conn.

WARNING: Only use this method if you know what you are doing!

Reading from or writing to the returned connection will end badly!

func (*Ctx) ConnID

func (c *Ctx) ConnID() uint64

ConnID returns unique connection ID.

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

func (*Ctx) ConnRequestNum

func (c *Ctx) ConnRequestNum() uint64

ConnRequestNum returns request sequence number for the current connection.

Sequence starts with 1.

func (*Ctx) ConnTime

func (c *Ctx) ConnTime() time.Time

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

func (*Ctx) Deadline

func (c *Ctx) Deadline() (deadline time.Time, ok bool)

Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results.

This method always returns 0, false and is only present to make Ctx implement the context interface.

func (*Ctx) Done

func (c *Ctx) Done() <-chan struct{}

Done returns a channel that's closed when work done on behalf of this context should be canceled. Done may return nil if this context can never be canceled. Successive calls to Done return the same value.

func (*Ctx) Err

func (c *Ctx) Err() error

Err returns a non-nil error value after Done is closed, successive calls to Err return the same error. If Done is not yet closed, Err returns nil. If Done is closed, Err returns a non-nil error explaining why: Canceled if the context was canceled (via server Shutdown) or DeadlineExceeded if the context's deadline passed.

func (*Ctx) Error

func (c *Ctx) Error(msg string, statusCode int)

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

Warning: this will reset the response headers and body already set!

func (*Ctx) Host

func (c *Ctx) Host() []byte

Host returns requested host.

The returned bytes are valid until your request handler returns.

func (*Ctx) ID

func (c *Ctx) ID() uint64

ID returns unique ID of the request.

func (*Ctx) IfModifiedSince

func (c *Ctx) 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 (*Ctx) IsConnect

func (c *Ctx) IsConnect() bool

IsConnect returns true if request method is CONNECT.

func (*Ctx) IsDelete

func (c *Ctx) IsDelete() bool

IsDelete returns true if request method is DELETE.

func (*Ctx) IsGet

func (c *Ctx) IsGet() bool

IsGet returns true if request method is GET.

func (*Ctx) IsHead

func (c *Ctx) IsHead() bool

IsHead returns true if request method is HEAD.

func (*Ctx) IsOptions

func (c *Ctx) IsOptions() bool

IsOptions returns true if request method is OPTIONS.

func (*Ctx) IsPatch

func (c *Ctx) IsPatch() bool

IsPatch returns true if request method is PATCH.

func (*Ctx) IsPost

func (c *Ctx) IsPost() bool

IsPost returns true if request method is POST.

func (*Ctx) IsPut

func (c *Ctx) IsPut() bool

IsPut returns true if request method is PUT.

func (*Ctx) IsTrace

func (c *Ctx) IsTrace() bool

IsTrace returns true if request method is TRACE.

func (*Ctx) LocalAddr

func (c *Ctx) LocalAddr() net.Addr

LocalAddr returns server address for the given request.

Always returns non-nil result.

func (*Ctx) LocalIP

func (c *Ctx) LocalIP() net.IP

LocalIP returns the server ip the request came to.

Always returns non-nil result.

func (*Ctx) Logger

func (c *Ctx) Logger() *zap.Logger

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

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 your request handler returns.

func (*Ctx) Method

func (c *Ctx) Method() []byte

Method return request method.

Returned value is valid until your request handler returns.

func (*Ctx) NotFound

func (c *Ctx) NotFound()

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

func (*Ctx) NotModified

func (c *Ctx) NotModified()

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

func (*Ctx) Path

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

Path returns requested path.

The returned bytes are valid until your request handler returns.

func (*Ctx) PostArgs

func (c *Ctx) PostArgs() *Args

PostArgs returns POST arguments.

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

See also QueryArgs, FormValue and FormFile.

These args are valid until your request handler returns.

func (*Ctx) PostBody

func (c *Ctx) PostBody() []byte

PostBody returns POST request body.

The returned bytes are valid until your request handler returns.

func (*Ctx) QueryArgs

func (c *Ctx) QueryArgs() *Args

QueryArgs returns query arguments from RequestURI.

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

See also PostArgs, FormValue and FormFile.

These args are valid until your request handler returns.

func (*Ctx) Redirect

func (c *Ctx) 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)
  • StatusPermanentRedirect (308)

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

The redirect uri may be either absolute or relative to the current request uri. Fasthttp will always send an absolute uri back to the client. To send a relative uri you can use the following code:

strLocation = []byte("Location") // Put this with your top level var () declarations.
ctx.Response.Header.SetCanonical(strLocation, "/relative?uri")
ctx.Response.SetStatusCode(fasthttp.StatusMovedPermanently)

func (*Ctx) RedirectBytes

func (c *Ctx) 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)
  • StatusPermanentRedirect (308)

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

The redirect uri may be either absolute or relative to the current request uri. Fasthttp will always send an absolute uri back to the client. To send a relative uri you can use the following code:

strLocation = []byte("Location") // Put this with your top level var () declarations.
ctx.Response.Header.SetCanonical(strLocation, "/relative?uri")
ctx.Response.SetStatusCode(fasthttp.StatusMovedPermanently)

func (*Ctx) Referer

func (c *Ctx) Referer() []byte

Referer returns request referer.

The returned bytes are valid until your request handler returns.

func (*Ctx) RemoteAddr

func (c *Ctx) RemoteAddr() net.Addr

RemoteAddr returns client address for the given request.

Always returns non-nil result.

func (*Ctx) RemoteIP

func (c *Ctx) RemoteIP() net.IP

RemoteIP returns the client ip the request came from.

Always returns non-nil result.

func (*Ctx) RequestURI

func (c *Ctx) RequestURI() []byte

RequestURI returns RequestURI.

The returned bytes are valid until your request handler returns.

func (*Ctx) ResetBody

func (c *Ctx) ResetBody()

ResetBody resets response body contents.

func (*Ctx) SetBody

func (c *Ctx) SetBody(body []byte)

SetBody sets response body to the given value.

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

func (*Ctx) SetBodyString

func (c *Ctx) SetBodyString(body string)

SetBodyString sets response body to the given value.

func (*Ctx) SetConnectionClose

func (c *Ctx) SetConnectionClose()

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

func (*Ctx) SetContentType

func (c *Ctx) SetContentType(contentType string)

SetContentType sets response Content-Type.

func (*Ctx) SetContentTypeBytes

func (c *Ctx) SetContentTypeBytes(contentType []byte)

SetContentTypeBytes sets response Content-Type.

It is safe modifying contentType buffer after function return.

func (*Ctx) SetRemoteAddr

func (c *Ctx) SetRemoteAddr(remoteAddr net.Addr)

SetRemoteAddr sets remote address to the given value.

Set nil value to resore default behaviour for using connection remote address.

func (*Ctx) SetStatusCode

func (c *Ctx) SetStatusCode(statusCode int)

SetStatusCode sets response status code.

func (*Ctx) String

func (c *Ctx) String() string

String returns unique string representation of the ctx.

The returned value may be useful for logging.

func (*Ctx) Success

func (c *Ctx) Success(contentType string, body []byte)

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

func (*Ctx) SuccessString

func (c *Ctx) SuccessString(contentType, body string)

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

func (*Ctx) Time

func (c *Ctx) Time() time.Time

Time returns Handler call time.

func (*Ctx) URI

func (c *Ctx) URI() *URI

URI returns requested uri.

This uri is valid until your request handler returns.

func (*Ctx) UserAgent

func (c *Ctx) UserAgent() []byte

UserAgent returns User-Agent header value from the request.

The returned bytes are valid until your request handler returns.

func (*Ctx) Value

func (c *Ctx) Value(key interface{}) interface{}

Value is no-op implementation for context.Context.

func (*Ctx) Write

func (c *Ctx) Write(p []byte) (int, error)

Write writes p into response body.

func (*Ctx) WriteString

func (c *Ctx) WriteString(s string) (int, error)

WriteString appends s to response body.

type ErrBrokenChunk

type ErrBrokenChunk struct {
	Reason string
}

ErrBrokenChunk is returned when server receives a broken chunked body (Transfer-Encoding: chunked).

func (*ErrBrokenChunk) Error

func (e *ErrBrokenChunk) Error() string

type ErrNothingRead

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

ErrNothingRead is returned when a keep-alive connection is closed, either because the remote closed it or because of a read timeout.

type ErrSmallBuffer

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 EscapeError

type EscapeError string

func (EscapeError) Error

func (e EscapeError) Error() string

type Handler

type Handler func(ctx *Ctx)

Handler must process incoming requests.

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

type InvalidHostError

type InvalidHostError string

func (InvalidHostError) Error

func (e InvalidHostError) Error() string

type Request

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 (*Request) AppendBody

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

AppendBody appends p to request body.

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

func (*Request) AppendBodyString

func (r *Request) AppendBodyString(s string)

AppendBodyString appends s to request body.

func (*Request) Body

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

Body returns request body.

The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead.

func (*Request) BodyWriteTo

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

BodyWriteTo writes request body to w.

func (*Request) ConnectionClose

func (r *Request) ConnectionClose() bool

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

func (*Request) ContinueReadBody

func (r *Request) ContinueReadBody(reader *bufio.Reader) 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

func (r *Request) CopyTo(dst *Request)

CopyTo copies req contents to dst except of body stream.

func (*Request) Host

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

Host returns the host for the given request.

func (*Request) MayContinue

func (r *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) PostArgs

func (r *Request) PostArgs() *Args

PostArgs returns POST arguments.

func (*Request) Read

func (r *Request) Read(reader *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) ReadBody

func (r *Request) ReadBody(reader *bufio.Reader, contentLength int) error

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

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

func (*Request) ReleaseBody

func (r *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) RequestURI

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

RequestURI returns request's URI.

func (*Request) Reset

func (r *Request) Reset()

Reset clears request contents.

func (*Request) ResetBody

func (r *Request) ResetBody()

ResetBody resets request body.

func (*Request) SetBody

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

SetBody sets request body.

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

func (*Request) SetBodyRaw

func (r *Request) SetBodyRaw(body []byte)

SetBodyRaw sets response body, but without copying it.

From this point onward the body argument must not be changed.

func (*Request) SetBodyString

func (r *Request) SetBodyString(body string)

SetBodyString sets request body.

func (*Request) SetConnectionClose

func (r *Request) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*Request) SetHost

func (r *Request) SetHost(host string)

SetHost sets host for the request.

func (*Request) SetHostBytes

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

SetHostBytes sets host for the request.

func (*Request) SetRequestURI

func (r *Request) SetRequestURI(requestURI string)

SetRequestURI sets RequestURI.

func (*Request) SetRequestURIBytes

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

SetRequestURIBytes sets RequestURI.

func (*Request) SetURI

func (r *Request) SetURI(uri *URI)

SetURI initializes request URI Use this method if a single URI may be reused across multiple requests. Otherwise, you can just use SetRequestURI() and it will be parsed as new URI. The URI is copied and can be safely modified later.

func (*Request) String

func (r *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) URI

func (r *Request) URI() *URI

URI returns request URI

func (*Request) Write

func (r *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

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

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

type RequestConfig

type RequestConfig struct {
	// ReadTimeout is the maximum duration for reading the entire
	// request body.
	// a zero value means that default values will be honored
	ReadTimeout time.Duration
	// WriteTimeout is the maximum duration before timing out
	// writes of the response.
	// a zero value means that default values will be honored
	WriteTimeout time.Duration
}

RequestConfig configure the per request deadline and body limits

type RequestHeader

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

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

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

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.

the Content-Type, Content-Length, Connection, Cookie, Transfer-Encoding, Host and User-Agent headers can only be set once and will overwrite the previous value.

func (*RequestHeader) AddBytesV

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

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

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

func (*RequestHeader) ConnectionClose

func (h *RequestHeader) ConnectionClose() bool

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

func (*RequestHeader) ConnectionUpgrade

func (h *RequestHeader) ConnectionUpgrade() bool

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

func (*RequestHeader) ContentLength

func (h *RequestHeader) ContentLength() int

ContentLength returns Content-Length header value.

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

func (*RequestHeader) ContentType

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

ContentType returns Content-Type header value.

func (*RequestHeader) Cookie

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

Cookie returns cookie for the given key.

func (*RequestHeader) CookieBytes

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

CookieBytes returns cookie for the given key.

func (*RequestHeader) CopyTo

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

CopyTo copies all the headers to dst.

func (*RequestHeader) Del

func (h *RequestHeader) Del(key string)

Del deletes header with the given key.

func (*RequestHeader) DelAllCookies

func (h *RequestHeader) DelAllCookies()

DelAllCookies removes all the cookies from request headers.

func (*RequestHeader) DelBytes

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

DelBytes deletes header with the given key.

func (*RequestHeader) DelCookie

func (h *RequestHeader) DelCookie(key string)

DelCookie removes cookie under the given key.

func (*RequestHeader) DelCookieBytes

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

DelCookieBytes removes cookie under the given key.

func (*RequestHeader) DisableNormalizing

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

func (h *RequestHeader) EnableNormalizing()

EnableNormalizing enables header names' normalization.

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

This is enabled by default unless disabled using DisableNormalizing()

func (*RequestHeader) HasAcceptEncoding

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

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

func (*RequestHeader) HasAcceptEncodingBytes

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

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

func (*RequestHeader) Header

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

Header returns request header representation.

The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead.

func (*RequestHeader) Host

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

Host returns Host header value.

func (*RequestHeader) IsConnect

func (h *RequestHeader) IsConnect() bool

IsConnect returns true if request method is CONNECT.

func (*RequestHeader) IsDelete

func (h *RequestHeader) IsDelete() bool

IsDelete returns true if request method is DELETE.

func (*RequestHeader) IsGet

func (h *RequestHeader) IsGet() bool

IsGet returns true if request method is GET.

func (*RequestHeader) IsHTTP11

func (h *RequestHeader) IsHTTP11() bool

IsHTTP11 returns true if the request is HTTP/1.1.

func (*RequestHeader) IsHead

func (h *RequestHeader) IsHead() bool

IsHead returns true if request method is HEAD.

func (*RequestHeader) IsOptions

func (h *RequestHeader) IsOptions() bool

IsOptions returns true if request method is OPTIONS.

func (*RequestHeader) IsPatch

func (h *RequestHeader) IsPatch() bool

IsPatch returns true if request method is PATCH.

func (*RequestHeader) IsPost

func (h *RequestHeader) IsPost() bool

IsPost returns true if request method is POST.

func (*RequestHeader) IsPut

func (h *RequestHeader) IsPut() bool

IsPut returns true if request method is PUT.

func (*RequestHeader) IsTrace

func (h *RequestHeader) IsTrace() bool

IsTrace returns true if request method is TRACE.

func (*RequestHeader) Len

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

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

Method returns HTTP request method.

func (*RequestHeader) MultipartFormBoundary

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

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

func (*RequestHeader) Peek

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

Peek returns header value for the given key.

The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead.

func (*RequestHeader) PeekBytes

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

PeekBytes returns header value for the given key.

The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead.

func (*RequestHeader) Protocol

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

Protocol returns HTTP protocol.

func (*RequestHeader) RawHeaders

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

RawHeaders returns raw header key/value bytes.

Depending on server configuration, header keys may be normalized to capital-case in place.

This copy is set aside during parsing, so empty slice is returned for all cases where parsing did not happen. Similarly, request line is not stored during parsing and can not be returned.

The slice is not safe to use after the handler returns.

func (*RequestHeader) Read

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

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

Referer returns Referer header value.

func (*RequestHeader) RequestURI

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

RequestURI returns RequestURI from the first HTTP request line.

func (*RequestHeader) Reset

func (h *RequestHeader) Reset()

Reset clears request header.

func (*RequestHeader) ResetConnectionClose

func (h *RequestHeader) ResetConnectionClose()

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

func (*RequestHeader) Set

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

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

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

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

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

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

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

func (*RequestHeader) SetConnectionClose

func (h *RequestHeader) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*RequestHeader) SetContentLength

func (h *RequestHeader) SetContentLength(contentLength int)

SetContentLength sets Content-Length header value.

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

func (*RequestHeader) SetContentType

func (h *RequestHeader) SetContentType(contentType string)

SetContentType sets Content-Type header value.

func (*RequestHeader) SetContentTypeBytes

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

SetContentTypeBytes sets Content-Type header value.

func (*RequestHeader) SetCookie

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

SetCookie sets 'key: value' cookies.

func (*RequestHeader) SetCookieBytesK

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

SetCookieBytesK sets 'key: value' cookies.

func (*RequestHeader) SetCookieBytesKV

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

SetCookieBytesKV sets 'key: value' cookies.

func (*RequestHeader) SetHost

func (h *RequestHeader) SetHost(host string)

SetHost sets Host header value.

func (*RequestHeader) SetHostBytes

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

SetHostBytes sets Host header value.

func (*RequestHeader) SetMethod

func (h *RequestHeader) SetMethod(method string)

SetMethod sets HTTP request method.

func (*RequestHeader) SetMethodBytes

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

SetMethodBytes sets HTTP request method.

func (*RequestHeader) SetMultipartFormBoundary

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

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

func (h *RequestHeader) SetProtocol(method string)

SetProtocol sets HTTP request protocol.

func (*RequestHeader) SetProtocolBytes

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

SetProtocolBytes sets HTTP request protocol.

func (*RequestHeader) SetReferer

func (h *RequestHeader) SetReferer(referer string)

SetReferer sets Referer header value.

func (*RequestHeader) SetRefererBytes

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

SetRefererBytes sets Referer header value.

func (*RequestHeader) SetRequestURI

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

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

func (h *RequestHeader) SetUserAgent(userAgent string)

SetUserAgent sets User-Agent header value.

func (*RequestHeader) SetUserAgentBytes

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

SetUserAgentBytes sets User-Agent header value.

func (*RequestHeader) String

func (h *RequestHeader) String() string

String returns request header representation.

func (*RequestHeader) UserAgent

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

UserAgent returns User-Agent header value.

func (*RequestHeader) VisitAll

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.

To get the headers in order they were received use VisitAllInOrder.

func (*RequestHeader) VisitAllCookie

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

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

VisitAllInOrder calls f for each header in the order they were received.

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.

This function is slightly slower than VisitAll because it has to reparse the raw headers to get the order.

func (*RequestHeader) Write

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

Write writes request header to w.

func (*RequestHeader) WriteTo

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

WriteTo writes request header to w.

WriteTo implements io.WriterTo interface.

type Response

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 (*Response) AppendBody

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

AppendBody appends p to response body.

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

func (*Response) AppendBodyString

func (r *Response) AppendBodyString(s string)

AppendBodyString appends s to response body.

func (*Response) Body

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

Body returns response body.

The returned value is valid until the response is released, either though ReleaseResponse or your request handler returning. Do not store references to returned value. Make copies instead.

func (*Response) BodyWriteTo

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

BodyWriteTo writes response body to w.

func (*Response) ConnectionClose

func (r *Response) ConnectionClose() bool

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

func (*Response) CopyTo

func (r *Response) CopyTo(dst *Response)

CopyTo copies resp contents to dst except of body stream.

func (*Response) LocalAddr

func (r *Response) LocalAddr() net.Addr

LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.

func (*Response) Read

func (r *Response) Read(reader *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) ReleaseBody

func (r *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) RemoteAddr

func (r *Response) RemoteAddr() net.Addr

RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.

func (*Response) Reset

func (r *Response) Reset()

Reset clears response contents.

func (*Response) ResetBody

func (r *Response) ResetBody()

ResetBody resets response body.

func (*Response) SetBody

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

SetBody sets response body.

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

func (*Response) SetBodyRaw

func (r *Response) SetBodyRaw(body []byte)

SetBodyRaw sets response body, but without copying it.

From this point onward the body argument must not be changed.

func (*Response) SetBodyString

func (r *Response) SetBodyString(body string)

SetBodyString sets response body.

func (*Response) SetConnectionClose

func (r *Response) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*Response) SetStatusCode

func (r *Response) SetStatusCode(statusCode int)

SetStatusCode sets response status code.

func (*Response) StatusCode

func (r *Response) StatusCode() int

StatusCode returns response status code.

func (*Response) String

func (r *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) Write

func (r *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) WriteTo

func (r *Response) WriteTo(w io.Writer) (int64, error)

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

type ResponseHeader

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

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.

the Content-Type, Content-Length, Connection, Server, Set-Cookie, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value.

func (*ResponseHeader) AddBytesK

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.

the Content-Type, Content-Length, Connection, Server, Set-Cookie, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value.

func (*ResponseHeader) AddBytesKV

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.

the Content-Type, Content-Length, Connection, Server, Set-Cookie, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value.

func (*ResponseHeader) AddBytesV

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.

the Content-Type, Content-Length, Connection, Server, Set-Cookie, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value.

func (*ResponseHeader) AppendBytes

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

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

func (*ResponseHeader) ConnectionClose

func (h *ResponseHeader) ConnectionClose() bool

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

func (*ResponseHeader) ConnectionUpgrade

func (h *ResponseHeader) ConnectionUpgrade() bool

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

func (*ResponseHeader) ContentLength

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

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

ContentType returns Content-Type header value.

func (*ResponseHeader) Cookie

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

func (h *ResponseHeader) CopyTo(dst *ResponseHeader)

CopyTo copies all the headers to dst.

func (*ResponseHeader) Del

func (h *ResponseHeader) Del(key string)

Del deletes header with the given key.

func (*ResponseHeader) DelAllCookies

func (h *ResponseHeader) DelAllCookies()

DelAllCookies removes all the cookies from response headers.

func (*ResponseHeader) DelBytes

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

DelBytes deletes header with the given key.

func (*ResponseHeader) DelClientCookie

func (h *ResponseHeader) DelClientCookie(key string)

DelClientCookie instructs the client to remove the given cookie. This doesn't work for a cookie with specific domain or path, you should delete it manually like:

c := AcquireCookie()
c.SetKey(key)
c.SetDomain("example.com")
c.SetPath("/path")
c.SetExpire(CookieExpireDelete)
h.SetCookie(c)
ReleaseCookie(c)

Use DelCookie if you want just removing the cookie from response header.

func (*ResponseHeader) DelClientCookieBytes

func (h *ResponseHeader) DelClientCookieBytes(key []byte)

DelClientCookieBytes instructs the client to remove the given cookie. This doesn't work for a cookie with specific domain or path, you should delete it manually like:

c := AcquireCookie()
c.SetKey(key)
c.SetDomain("example.com")
c.SetPath("/path")
c.SetExpire(CookieExpireDelete)
h.SetCookie(c)
ReleaseCookie(c)

Use DelCookieBytes if you want just removing the cookie from response header.

func (*ResponseHeader) DelCookie

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

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

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

func (h *ResponseHeader) EnableNormalizing()

EnableNormalizing enables header names' normalization.

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

This is enabled by default unless disabled using DisableNormalizing()

func (*ResponseHeader) Header

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

Header returns response header representation.

The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead.

func (*ResponseHeader) IsHTTP11

func (h *ResponseHeader) IsHTTP11() bool

IsHTTP11 returns true if the response is HTTP/1.1.

func (*ResponseHeader) Len

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

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

Peek returns header value for the given key.

The returned value is valid until the response is released, either though ReleaseResponse or your request handler returning. Do not store references to the returned value. Make copies instead.

func (*ResponseHeader) PeekBytes

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

PeekBytes returns header value for the given key.

The returned value is valid until the response is released, either though ReleaseResponse or your request handler returning. Do not store references to returned value. Make copies instead.

func (*ResponseHeader) PeekCookie

func (h *ResponseHeader) PeekCookie(key string) []byte

PeekCookie is able to returns cookie by a given key from response.

func (*ResponseHeader) Protocol

func (h *ResponseHeader) Protocol() []byte

Protocol returns response protocol bytes.

func (*ResponseHeader) Read

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

func (h *ResponseHeader) Reset()

Reset clears response header.

func (*ResponseHeader) ResetConnectionClose

func (h *ResponseHeader) ResetConnectionClose()

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

func (*ResponseHeader) Server

func (h *ResponseHeader) Server() []byte

Server returns Server header value.

func (*ResponseHeader) Set

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

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

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

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

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

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

func (*ResponseHeader) SetConnectionClose

func (h *ResponseHeader) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*ResponseHeader) SetContentLength

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

func (h *ResponseHeader) SetContentRange(startPos, endPos, contentLength int)

SetContentRange sets 'Content-Range: bytes startPos-endPos/contentLength' header.

func (*ResponseHeader) SetContentType

func (h *ResponseHeader) SetContentType(contentType string)

SetContentType sets Content-Type header value.

func (*ResponseHeader) SetContentTypeBytes

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

SetContentTypeBytes sets Content-Type header value.

func (*ResponseHeader) SetCookie

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

func (h *ResponseHeader) SetLastModified(t time.Time)

SetLastModified sets 'Last-Modified' header to the given value.

func (*ResponseHeader) SetNoDefaultContentType

func (h *ResponseHeader) SetNoDefaultContentType(noDefaultContentType bool)

SetNoDefaultContentType allows you to control if a default Content-Type header will be set (false) or not (true).

func (*ResponseHeader) SetProtocol

func (h *ResponseHeader) SetProtocol(protocol []byte)

SetProtocol sets response protocol bytes.

func (*ResponseHeader) SetServer

func (h *ResponseHeader) SetServer(server string)

SetServer sets Server header value.

func (*ResponseHeader) SetServerBytes

func (h *ResponseHeader) SetServerBytes(server []byte)

SetServerBytes sets Server header value.

func (*ResponseHeader) SetStatusCode

func (h *ResponseHeader) SetStatusCode(statusCode int)

SetStatusCode sets response status code.

func (*ResponseHeader) SetStatusMessage

func (h *ResponseHeader) SetStatusMessage(statusMessage []byte)

SetStatusMessage sets response status message bytes.

func (*ResponseHeader) StatusCode

func (h *ResponseHeader) StatusCode() int

StatusCode returns response status code.

func (*ResponseHeader) StatusMessage

func (h *ResponseHeader) StatusMessage() []byte

StatusMessage returns response status message.

func (*ResponseHeader) String

func (h *ResponseHeader) String() string

String returns response header representation.

func (*ResponseHeader) VisitAll

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

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

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

Write writes response header to w.

func (*ResponseHeader) WriteTo

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

WriteTo writes response header to w.

WriteTo implements io.WriterTo interface.

type ServeHandler

type ServeHandler func(c net.Conn) error

ServeHandler must process tls.Config.NextProto negotiated requests.

type Server

type Server struct {

	// Handler for processing incoming requests.
	//
	// Take into account that no `panic` recovery is done by `fasthttp` (thus any `panic` will take down the entire server).
	// Instead the user should use `recover` to handle these situations.
	Handler Handler

	// ErrorHandler for returning a response in case of an error while receiving or parsing the request.
	//
	// The following is a non-exhaustive list of errors that can be expected as argument:
	//   * io.EOF
	//   * io.ErrUnexpectedEOF
	//   * ErrGetOnly
	//   * ErrSmallBuffer
	//   * ErrBodyTooLarge
	//   * ErrBrokenChunks
	ErrorHandler func(ctx *Ctx, err error)

	// HeaderReceived is called after receiving the header
	//
	// non zero RequestConfig field values will overwrite the default configs
	HeaderReceived func(header *RequestHeader) RequestConfig

	// ContinueHandler is called after receiving the Expect 100 Continue Header
	//
	// https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3
	// https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.1
	// Using ContinueHandler a server can make decisioning on whether or not
	// to read a potentially large request body based on the headers
	//
	// The default is to automatically read request bodies of Expect 100 Continue requests
	// like they are normal requests
	ContinueHandler func(header *RequestHeader) bool

	// 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.
	//
	// DefaultWorkers is used if not set.
	//
	// Workers only works if you either call Serve once, or only ServeConn multiple times.
	// It works with ListenAndServe as well.
	Workers int

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

	// ReadTimeout is the amount of time allowed to read
	// the full request including body. The connection's read
	// deadline is reset when the connection opens, or for
	// keep-alive connections after the first byte has been read.
	//
	// By default request read timeout is unlimited.
	ReadTimeout time.Duration

	// WriteTimeout is the maximum duration before timing out
	// writes of the response. It is reset after the request handler
	// has returned.
	//
	// By default response write timeout is unlimited.
	WriteTimeout time.Duration

	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alive is enabled. If IdleTimeout
	// is zero, the value of ReadTimeout is used.
	IdleTimeout time.Duration

	// Period between tcp keep-alive messages.
	//
	// TCP keep-alive period is determined by operation system by default.
	TCPKeepalivePeriod 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

	// Whether to enable tcp keep-alive connections.
	//
	// Whether the operating system should send tcp keep-alive messages on the tcp connection.
	//
	// By default tcp keep-alive connections are disabled.
	TCPKeepalive 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

	// Will not log potentially sensitive content in error logs
	//
	// This option is useful for servers that handle sensitive data
	// in the request/response.
	//
	// Server logs all full errors by default.
	SecureErrorLogMessage 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/go-faster/hx/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

	// SleepWhenConcurrencyLimitsExceeded is a duration to be slept of if
	// the concurrency limit in exceeded (default [when is 0]: don't sleep
	// and accept new connections immediately).
	SleepWhenConcurrencyLimitsExceeded time.Duration

	// NoDefaultServerHeader, when set to true, causes the default Server header
	// to be excluded from the Response.
	//
	// The default Server header value is the value of the Name field or an
	// internal default value in its absence. With this option set to true,
	// the only time a Server header will be sent is if a non-zero length
	// value is explicitly provided during a request.
	NoDefaultServerHeader bool

	// NoDefaultDate, when set to true, causes the default Date
	// header to be excluded from the Response.
	//
	// The default Date header value is the current date value. When
	// set to true, the Date will not be present.
	NoDefaultDate bool

	// NoDefaultContentType, when set to true, causes the default Content-Type
	// header to be excluded from the Response.
	//
	// The default Content-Type header value is the internal default value. When
	// set to true, the Content-Type will not be present.
	NoDefaultContentType bool

	// CloseOnShutdown when true adds a `Connection: close` header when the server is shutting down.
	CloseOnShutdown bool

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

	// Logger, which is used by Ctx.Logger().
	//
	// Nop by default.
	Logger *zap.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.

Example
package main

import (
	"fmt"
	"log"

	"github.com/go-faster/hx"
)

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

	// Create custom server.
	s := &hx.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)
	}
}
Output:

func (*Server) GetOpenConnectionsCount

func (s *Server) GetOpenConnectionsCount() int32

GetOpenConnectionsCount returns a number of opened connections.

This function is intended be used by monitoring systems

func (*Server) ListenAndServe

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.

Accepted connections are configured to enable TCP keep-alives.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context, ln net.Listener) error

Serve serves incoming connections from the given listener.

Serve blocks until the given listener returns permanent error.

func (*Server) ServeConn

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.

type URI

type URI struct {

	// Path values are sent as-is without normalization
	//
	// Disabled path normalization may be useful for proxying incoming requests
	// to servers that are expecting paths to be forwarded as-is.
	//
	// By default path values are normalized, i.e.
	// extra slashes are removed, special characters are encoded.
	DisablePathNormalizing bool
	// 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

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

func (u *URI) AppendBytes(dst []byte) []byte

AppendBytes appends full uri to dst and returns the extended dst.

func (*URI) CopyTo

func (u *URI) CopyTo(dst *URI)

CopyTo copies uri contents to dst.

func (*URI) FullURI

func (u *URI) FullURI() []byte

FullURI returns full uri in the form {Scheme}://{Host}{RequestURI}#{Hash}.

The returned bytes are valid until the next URI method call.

func (*URI) Hash

func (u *URI) Hash() []byte

Hash returns URI hash, i.e. qwe of http://aaa.com/foo/bar?baz=123#qwe .

The returned bytes are valid until the next URI method call.

func (*URI) Host

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.

The returned bytes are valid until the next URI method call.

func (*URI) LastPathSegment

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.

The returned bytes are valid until the next URI method call.

func (*URI) Parse

func (u *URI) Parse(host, uri []byte) error

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

func (u *URI) Password() []byte

Password returns URI password

The returned bytes are valid until the next URI method call.

func (*URI) Path

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 bytes are valid until the next URI method call.

func (*URI) PathOriginal

func (u *URI) PathOriginal() []byte

PathOriginal returns the original path from requestURI passed to URI.Parse().

The returned bytes are valid until the next URI method call.

func (*URI) QueryArgs

func (u *URI) QueryArgs() *Args

QueryArgs returns query args.

The returned args are valid until the next URI method call.

func (*URI) QueryString

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 bytes are valid until the next URI method call.

func (*URI) RequestURI

func (u *URI) RequestURI() []byte

RequestURI returns RequestURI - i.e. URI without Scheme and Host.

func (*URI) Reset

func (u *URI) Reset()

Reset clears uri.

func (*URI) Scheme

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 bytes are valid until the next URI method call.

func (*URI) SetHash

func (u *URI) SetHash(hash string)

SetHash sets URI hash.

func (*URI) SetHashBytes

func (u *URI) SetHashBytes(hash []byte)

SetHashBytes sets URI hash.

func (*URI) SetHost

func (u *URI) SetHost(host string)

SetHost sets host for the uri.

func (*URI) SetHostBytes

func (u *URI) SetHostBytes(host []byte)

SetHostBytes sets host for the uri.

func (*URI) SetPassword

func (u *URI) SetPassword(password string)

SetPassword sets URI password.

func (*URI) SetPasswordBytes

func (u *URI) SetPasswordBytes(password []byte)

SetPasswordBytes sets URI password.

func (*URI) SetPath

func (u *URI) SetPath(path string)

SetPath sets URI path.

func (*URI) SetPathBytes

func (u *URI) SetPathBytes(path []byte)

SetPathBytes sets URI path.

func (*URI) SetQueryString

func (u *URI) SetQueryString(queryString string)

SetQueryString sets URI query string.

func (*URI) SetQueryStringBytes

func (u *URI) SetQueryStringBytes(queryString []byte)

SetQueryStringBytes sets URI query string.

func (*URI) SetScheme

func (u *URI) SetScheme(scheme string)

SetScheme sets URI scheme, i.e. http, https, ftp, etc.

func (*URI) SetSchemeBytes

func (u *URI) SetSchemeBytes(scheme []byte)

SetSchemeBytes sets URI scheme, i.e. http, https, ftp, etc.

func (*URI) SetUsername

func (u *URI) SetUsername(username string)

SetUsername sets URI username.

func (*URI) SetUsernameBytes

func (u *URI) SetUsernameBytes(username []byte)

SetUsernameBytes sets URI username.

func (*URI) String

func (u *URI) String() string

String returns full uri.

func (*URI) Update

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

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

func (u *URI) Username() []byte

Username returns URI username

The returned bytes are valid until the next URI method call.

func (*URI) WriteTo

func (u *URI) WriteTo(w io.Writer) (int64, error)

WriteTo writes full uri to w.

WriteTo implements io.WriterTo interface.

Directories

Path Synopsis
examples
Package fasthttputil provides utility functions for fasthttp.
Package fasthttputil provides utility functions for fasthttp.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL