http

package
v0.0.0-...-78e603a Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2025 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CompressNoCompression      = flate.NoCompression
	CompressBestSpeed          = flate.BestSpeed
	CompressBestCompression    = flate.BestCompression
	CompressDefaultCompression = 6  // flate.DefaultCompression
	CompressHuffmanOnly        = -2 // flate.HuffmanOnly
)

Supported compression levels.

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"
	HeaderProxyConnection = "Proxy-Connection"

	// 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" // #nosec G101
	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 (
	CompressZstdSpeedNotSet = iota
	CompressZstdBestSpeed
	CompressZstdDefault
	CompressZstdSpeedBetter
	CompressZstdBestCompression
)

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 DeprecatedNewlineIncludeContext atomic.Bool

DeprecatedNewlineIncludeContext is used to control whether the context of the header is included in the warning message about the deprecated newline separator. Warning: this can potentially leak sensitive information such as auth headers.

View Source
var ErrBadTrailer = errors.New("contain forbidden trailer")
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 = &timeoutError{}

ErrTimeout is returned from timed out calls.

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

Functions

func AppendDeflateBytes

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

AppendDeflateBytes appends deflated src to dst and returns the resulting dst.

func AppendDeflateBytesLevel

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

AppendDeflateBytesLevel appends deflated src to dst using the given compression level and returns the resulting dst.

Supported compression levels are:

  • CompressNoCompression
  • CompressBestSpeed
  • CompressBestCompression
  • CompressDefaultCompression
  • CompressHuffmanOnly

func AppendGunzipBytes

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

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

func AppendGzipBytes

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

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

func AppendGzipBytesLevel

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

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

Supported compression levels are:

  • CompressNoCompression
  • CompressBestSpeed
  • CompressBestCompression
  • CompressDefaultCompression
  • CompressHuffmanOnly

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 AppendInflateBytes

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

AppendInflateBytes appends inflated src to dst and returns the resulting 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 AppendUnzstdBytes

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

AppendUnzstdBytes appends unzstd src to dst and returns the resulting dst.

func AppendZstdBytes

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

AppendZstdBytes appends zstd src to dst and returns the resulting dst.

func AppendZstdBytesLevel

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

func NewFunc

func NewFunc(f func(ctx any)) func(ctx any) bool

NewFunc returns stackless wrapper for the function f.

Unlike f, the returned stackless wrapper doesn't use stack space on the goroutine that calls it. The wrapper may save a lot of stack space if the following conditions are met:

  • f doesn't contain blocking calls on network, I/O or channels;
  • f uses a lot of stack space;
  • the wrapper is called from high number of concurrent goroutines.

The stackless wrapper returns false if the call cannot be processed at the moment due to high load.

func NewStreamReader

func NewStreamReader(sw StreamWriter) io.ReadCloser

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

The returned reader may be passed to Response.SetBodyStream.

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

See also Response.SetBodyStreamWriter.

func 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 ReleaseRequest

func ReleaseRequest(req *Request)

ReleaseRequest returns req acquired via AcquireRequest to request pool.

func ReleaseRequestParser

func ReleaseRequestParser(p *Parser)

ReleaseRequestParser Release request parser

func ReleaseResponse

func ReleaseResponse(resp *Response)

ReleaseResponse returns resp acquired via AcquireResponse to response pool.

func ReleaseResponseParser

func ReleaseResponseParser(p *Parser)

ReleaseResponseParser Release response parser

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 StatusMessage

func StatusMessage(statusCode int) string

StatusMessage returns HTTP status message for the given status code.

func VisitHeaderParams

func VisitHeaderParams(b []byte, f func(key, value []byte) bool)

VisitHeaderParams calls f for each parameter in the given header bytes. It stops processing when f returns false or an invalid parameter is found. Parameter values may be quoted, in which case \ is treated as an escape character, and the value is unquoted before being passed to value. See: https://www.rfc-editor.org/rfc/rfc9110#section-5.6.6

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 WriteDeflate

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

WriteDeflate writes deflated p to w and returns the number of compressed bytes written to w.

func WriteDeflateLevel

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

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

Supported compression levels are:

  • CompressNoCompression
  • CompressBestSpeed
  • CompressBestCompression
  • CompressDefaultCompression
  • CompressHuffmanOnly

func WriteGunzip

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

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

func WriteGzip

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

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

func WriteGzipLevel

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

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

Supported compression levels are:

  • CompressNoCompression
  • CompressBestSpeed
  • CompressBestCompression
  • CompressDefaultCompression
  • CompressHuffmanOnly

func WriteInflate

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

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

func WriteUnzstd

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

WriteUnzstd writes unzstd p to w and returns the number of uncompressed bytes written to w.

func WriteZstdLevel

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

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

func (a *Args) All() iter.Seq2[[]byte, []byte]

All returns an iterator over key-value pairs from args.

The key and value may invalid outside the iteration loop. Make copies if you need to use them after the loop ends.

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 argument, 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 deprecated

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.

Deprecated: Use All instead.

func (*Args) WriteTo

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

WriteTo writes query string to w.

WriteTo implements io.WriterTo interface.

type Context

type Context struct {
	Request  *Request
	Response *Response
	Params   map[string]string
	Values   map[string]any
	Conn     metanet.Conn
	// contains filtered or unexported fields
}

Context represents HTTP request context.

func NewContext

func NewContext(req *Request, resp *Response, conn metanet.Conn) *Context

NewContext creates a new context.

func (*Context) Abort

func (c *Context) Abort()

Abort stops the execution of handlers.

func (*Context) Get

func (c *Context) Get(key string) (any, bool)

Get retrieves a value from context.

func (*Context) HTML

func (c *Context) HTML(statusCode int, html string)

HTML sends HTML response.

func (*Context) JSON

func (c *Context) JSON(statusCode int, data any)

JSON sends JSON response.

func (*Context) Next

func (c *Context) Next()

Next executes the next handler in the chain.

func (*Context) NotFound

func (c *Context) NotFound()

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

func (*Context) Param

func (c *Context) Param(key string) string

Param returns path parameter value.

func (*Context) PostForm

func (c *Context) PostForm(key string) string

PostForm returns POST form parameter value.

func (*Context) Query

func (c *Context) Query(key string) string

Query returns query parameter value.

func (*Context) Redirect

func (c *Context) Redirect(statusCode int, location string)

Redirect sends redirect response.

func (*Context) Set

func (c *Context) Set(key string, value any)

Set stores a value in context.

func (*Context) String

func (c *Context) String(statusCode int, format string, values ...any)

String sends string response.

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

func (c *Cookie) Partitioned() bool

Partitioned returns true if the cookie is partitioned.

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.

'max-age' is set when the maxAge is non-zero. That is, if maxAge = 0, the 'max-age' is unset. If maxAge < 0, it indicates that the cookie should be deleted immediately, equivalent to 'max-age=0'. This behavior is consistent with the Go standard library's net/http package.

func (*Cookie) SetPartitioned

func (c *Cookie) SetPartitioned(partitioned bool)

SetPartitioned sets the cookie's Partitioned flag to the given value. Set value Partitioned to true will set Secure to true and Path to / also to avoid browser rejection.

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 // third-party cookies are phasing out, use Partitioned cookies instead
)

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 HandlerFunc

type HandlerFunc func(ctx *Context)

HandlerFunc represents a handler function.

type InvalidHostError

type InvalidHostError string

func (InvalidHostError) Error

func (e InvalidHostError) Error() string

type MiddlewareFunc

type MiddlewareFunc func(next HandlerFunc) HandlerFunc

MiddlewareFunc represents a middleware function.

func CORS

func CORS() MiddlewareFunc

CORS middleware handles Cross-Origin Resource Sharing.

func Logger

func Logger() MiddlewareFunc

Logger middleware logs requests.

func Recovery

func Recovery() MiddlewareFunc

Recovery middleware recovers from panics.

type NewWriterFunc

type NewWriterFunc func(w io.Writer) Writer

NewWriterFunc must return new writer that will be wrapped into stackless writer.

type Param

type Param struct {
	Key   string
	Value string
}

Param represents a path parameter

type Params

type Params []Param

Params is a slice of Param

func (Params) ByName

func (ps Params) ByName(name string) string

ByName returns the value of the first Param which key matches the given name.

func (Params) Get

func (ps Params) Get(name string) (string, bool)

Get returns the value of the first Param which key matches the given name.

type ParseState

type ParseState int

ParseState HTTP protocol state

const (
	ParseStateHeader ParseState = iota
	ParseStateBody
	ParseStateComplete
)

type Parser

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

Parser HTTP parser

func AcquireRequestParser

func AcquireRequestParser() *Parser

AcquireRequestParser Get request parser

func AcquireResponseParser

func AcquireResponseParser() *Parser

AcquireResponseParser Get response parser

func NewParser

func NewParser(isRequest bool) *Parser

NewParser Create a new HTTP parser

func (*Parser) GetRequest

func (p *Parser) GetRequest() *Request

GetRequest Get parsing result

func (*Parser) GetResponse

func (p *Parser) GetResponse() *Response

func (*Parser) Parse

func (p *Parser) Parse(data []byte) (parsed int, complete bool, err error)

Parse HTTP data

func (*Parser) Release

func (p *Parser) Release()

Release parser

func (*Parser) Reset

func (p *Parser) Reset()

Reset parser

type Request

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

Request represents HTTP request.

func AcquireRequest

func AcquireRequest() *Request

AcquireRequest returns an empty Request instance from request pool.

func (*Request) AppendBodyRaw

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

AppendBodyRaw appends data to request body.

func (*Request) Body

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

Body returns request body.

func (*Request) BodyStream

func (req *Request) BodyStream() io.Reader

BodyStream returns io.Reader.

You must CloseBodyStream or ReleaseRequest after you use it.

func (*Request) BodyString

func (req *Request) BodyString() string

BodyString returns request body as string.

func (*Request) BodyWriter

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

BodyWriter returns writer for populating request body.

func (*Request) CloseBodyStream

func (req *Request) CloseBodyStream() error

CloseBodyStream closes body stream.

func (*Request) Host

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

Host returns request host.

func (*Request) HostString

func (req *Request) HostString() string

HostString returns request host as string.

func (*Request) IsBodyStream

func (req *Request) IsBodyStream() bool

IsBodyStream returns true if body is set via SetBodyStream*.

func (*Request) Method

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

Method returns request method.

func (*Request) MethodString

func (req *Request) MethodString() string

MethodString returns request method as string.

func (*Request) PostArgs

func (req *Request) PostArgs() *Args

PostArgs returns POST arguments.

func (*Request) QueryArgs

func (req *Request) QueryArgs() *Args

QueryArgs returns query arguments from URI.

func (*Request) RequestURI

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

RequestURI returns request URI.

func (*Request) Reset

func (req *Request) Reset()

Reset clears request contents.

func (*Request) ResetBody

func (req *Request) ResetBody()

ResetBody resets request body.

func (*Request) SetBody

func (req *Request) SetBody(body string)

SetBody sets request body from string.

func (*Request) SetBodyRaw

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

SetBodyRaw sets request body.

func (*Request) SetBodyStream

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

SetBodyStream sets request body stream and, optionally body size.

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

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

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

See also SetBodyStreamWriter.

func (*Request) SetBodyStreamWriter

func (req *Request) SetBodyStreamWriter(sw StreamWriter)

SetBodyStreamWriter registers the given sw for populating request body.

This function may be used in the following cases:

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

See also SetBodyStream.

func (*Request) SetHost

func (req *Request) SetHost(host string)

SetHost sets request host.

func (*Request) SetMethod

func (req *Request) SetMethod(method string)

SetMethod sets request method.

func (*Request) SetRequestURI

func (req *Request) SetRequestURI(requestURI string)

SetRequestURI sets request URI.

func (*Request) SetURI

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

SetURI sets request URI.

func (*Request) String

func (req *Request) String() string

String returns string representation of request.

func (*Request) URI

func (req *Request) URI() *URI

URI returns request URI.

func (*Request) Write

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

Write writes request to writer.

func (*Request) WriteDeflate

func (req *Request) WriteDeflate(p []byte) (int, error)

WriteDeflate writes deflated request body.

func (*Request) WriteDeflateLevel

func (req *Request) WriteDeflateLevel(p []byte, level int) (int, error)

WriteDeflateLevel writes deflated request body with specified compression level.

func (*Request) WriteGzip

func (req *Request) WriteGzip(p []byte) (int, error)

WriteGzip writes gzipped request body.

func (*Request) WriteGzipLevel

func (req *Request) WriteGzipLevel(p []byte, level int) (int, error)

WriteGzipLevel writes gzipped request body with specified compression level.

func (*Request) WriteZstd

func (req *Request) WriteZstd(p []byte) (int, error)

WriteZstd writes zstd compressed request body.

func (*Request) WriteZstdLevel

func (req *Request) WriteZstdLevel(p []byte, level int) (int, error)

WriteZstdLevel writes zstd compressed request body with specified compression level.

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.

If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked request body.

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.

If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked request body.

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, Transfer-Encoding, Host and User-Agent headers can only be set once and will overwrite the previous value, while the Cookie header will not clear previous cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked request body.

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.

If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked request body.

func (*RequestHeader) AddTrailer

func (h *RequestHeader) AddTrailer(trailer string) error

AddTrailer add Trailer header value for chunked response to indicate which headers will be sent after the body.

Use Set to set the trailer header later.

Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages.

The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)

Return ErrBadTrailer if contain any forbidden trailers.

func (*RequestHeader) AddTrailerBytes

func (h *RequestHeader) AddTrailerBytes(trailer []byte) (err error)

AddTrailerBytes add Trailer header value for chunked response to indicate which headers will be sent after the body.

Use Set to set the trailer header later.

Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages.

The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)

Return ErrBadTrailer if contain any forbidden trailers.

func (*RequestHeader) All

func (h *RequestHeader) All() iter.Seq2[[]byte, []byte]

All returns an iterator over key-value pairs in h.

The key and value may invalid outside the iteration loop. Copy key and/or value contents for each iteration if you need retaining them.

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

func (*RequestHeader) AllInOrder

func (h *RequestHeader) AllInOrder() iter.Seq2[[]byte, []byte]

AllInOrder returns an iterator over key-value pairs in h in the order they were received.

The key and value may invalid outside the iteration loop. Copy key and/or value contents for each iteration if you need retaining them.

The returned iterator is slightly slower than All because it has to reparse the raw headers to get the order.

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

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

ContentEncoding returns Content-Encoding header value.

func (*RequestHeader) ContentLength

func (h *RequestHeader) ContentLength() int

ContentLength returns Content-Length header value.

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

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

func (h *RequestHeader) Cookies() iter.Seq2[[]byte, []byte]

Cookies returns an iterator over key-value pairs request cookie in h.

The key and value may invalid outside the iteration loop. Copy key and/or value contents for each iteration if you need retaining them.

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

func (h *RequestHeader) DisableSpecialHeader()

DisableSpecialHeader disables special header processing. fasthttp will not set any special headers for you, such as Host, Content-Type, User-Agent, etc. You must set everything yourself. If RequestHeader.Read() is called, special headers will be ignored. This can be used to control case and order of special headers. This is generally not recommended.

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

func (h *RequestHeader) EnableSpecialHeader()

EnableSpecialHeader enables special header processing. fasthttp will send Host, Content-Type, User-Agent, etc headers for you. This is suggested and enabled by default.

func (*RequestHeader) Get

func (h *RequestHeader) Get(key string) string

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.

Headers that set as Trailer will not represent. Use TrailerHeader for trailers.

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 header 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) PeekAll

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

PeekAll returns all header value for the given key.

The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Any future calls to the Peek* will modify the returned value. 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) PeekKeys

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

PeekKeys return all header keys.

The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Any future calls to the Peek* will modify the returned value. Do not store references to returned value. Make copies instead.

func (*RequestHeader) PeekTrailerKeys

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

PeekTrailerKeys return all trailer keys.

The returned value is valid until the request is released, either though ReleaseResponse or your request handler returning. Any future calls to the Peek* will modify the returned value. 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) ReadTrailer

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

ReadTrailer reads response trailer header from r.

io.EOF is returned if r is closed before reading the first 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.

Please note that the Cookie header will not clear previous cookies, delete cookies before calling in order to reset cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked request body.

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.

Please note that the Cookie header will not clear previous cookies, delete cookies before calling in order to reset cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked request body.

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.

Please note that the Cookie header will not clear previous cookies, delete cookies before calling in order to reset cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked request body.

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.

Please note that the Cookie header will not clear previous cookies, delete cookies before calling in order to reset cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked request body.

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.

Please note that the Cookie header will not clear previous cookies, delete cookies before calling in order to reset cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked request body.

func (*RequestHeader) SetConnectionClose

func (h *RequestHeader) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*RequestHeader) SetContentEncoding

func (h *RequestHeader) SetContentEncoding(contentEncoding string)

SetContentEncoding sets Content-Encoding header value.

func (*RequestHeader) SetContentEncodingBytes

func (h *RequestHeader) SetContentEncodingBytes(contentEncoding []byte)

SetContentEncodingBytes sets Content-Encoding header value.

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

func (h *RequestHeader) SetNoDefaultContentType(noDefaultContentType bool)

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

func (*RequestHeader) SetNonSpecial

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

SetNonSpecial directly put into map i.e. not a basic header.

func (*RequestHeader) SetProtocol

func (h *RequestHeader) SetProtocol(protocol string)

SetProtocol sets HTTP request protocol.

func (*RequestHeader) SetProtocolBytes

func (h *RequestHeader) SetProtocolBytes(protocol []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) SetTrailer

func (h *RequestHeader) SetTrailer(trailer string) error

SetTrailer sets header Trailer value for chunked response to indicate which headers will be sent after the body.

Use Set to set the trailer header later.

Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages.

The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)

Return ErrBadTrailer if contain any forbidden trailers.

func (*RequestHeader) SetTrailerBytes

func (h *RequestHeader) SetTrailerBytes(trailer []byte) error

SetTrailerBytes sets Trailer header value for chunked response to indicate which headers will be sent after the body.

Use Set to set the trailer header later.

Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages.

The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)

Return ErrBadTrailer if contain any forbidden trailers.

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

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

TrailerHeader returns request trailer header representation.

Trailers will only be received with chunked transfer.

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

func (h *RequestHeader) Trailers() iter.Seq[[]byte]

Trailers returns an iterator over trailers in h.

The value of trailer may invalid outside the iteration loop.

func (*RequestHeader) UserAgent

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

UserAgent returns User-Agent header value.

func (*RequestHeader) VisitAll deprecated

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.

Deprecated: Use All instead.

func (*RequestHeader) VisitAllCookie deprecated

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.

Deprecated: Use Cookies instead.

func (*RequestHeader) VisitAllInOrder deprecated

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.

Deprecated: Use AllInOrder instead.

func (*RequestHeader) VisitAllTrailer deprecated

func (h *RequestHeader) VisitAllTrailer(f func(value []byte))

VisitAllTrailer calls f for each response Trailer.

f must not retain references to value after returning.

Deprecated: Use Trailers instead.

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 {
	Header ResponseHeader
	// contains filtered or unexported fields
}

Response represents HTTP response.

func AcquireResponse

func AcquireResponse() *Response

AcquireResponse returns an empty Response instance from response pool.

func (*Response) AppendBody

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

AppendBody appends data to response body.

func (*Response) AppendBodyRaw

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

AppendBodyRaw appends data to response body.

func (*Response) AppendBodyString

func (resp *Response) AppendBodyString(s string)

AppendBodyString appends string to response body.

func (*Response) Body

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

Body returns response body.

func (*Response) BodyStream

func (resp *Response) BodyStream() io.Reader

BodyStream returns io.Reader.

You must CloseBodyStream or ReleaseResponse after you use it.

func (*Response) BodyString

func (resp *Response) BodyString() string

BodyString returns response body as string.

func (*Response) BodyWriter

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

BodyWriter returns writer for populating response body.

func (*Response) CloseBodyStream

func (resp *Response) CloseBodyStream() error

CloseBodyStream closes body stream.

func (*Response) ConnectionClose

func (resp *Response) ConnectionClose() bool

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

func (*Response) ContentLength

func (resp *Response) ContentLength() int

ContentLength returns Content-Length header value.

func (*Response) ContentType

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

ContentType returns Content-Type header value.

func (*Response) IsBodyStream

func (resp *Response) IsBodyStream() bool

IsBodyStream returns true if body is set via SetBodyStream*.

func (*Response) Redirect

func (resp *Response) Redirect(uri string, statusCode int)

Redirect sets response for redirect.

func (*Response) Reset

func (resp *Response) Reset()

Reset clears response contents.

func (*Response) ResetBody

func (resp *Response) ResetBody()

ResetBody resets response body.

func (*Response) Set

func (resp *Response) Set(key, value string)

Set sets response header.

func (*Response) SetBody

func (resp *Response) SetBody(body string)

SetBody sets response body from string.

func (*Response) SetBodyRaw

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

SetBodyRaw sets response body.

func (*Response) SetBodyStream

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

SetBodyStream sets response body stream and, optionally body size.

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

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

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

See also SetBodyStreamWriter.

func (*Response) SetBodyStreamWriter

func (resp *Response) SetBodyStreamWriter(sw StreamWriter)

SetBodyStreamWriter registers the given sw for populating response body.

This function may be used in the following cases:

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

See also SetBodyStream.

func (*Response) SetConnectionClose

func (resp *Response) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*Response) SetContentLength

func (resp *Response) SetContentLength(contentLength int)

SetContentLength sets Content-Length header.

func (*Response) SetContentType

func (resp *Response) SetContentType(contentType string)

SetContentType sets Content-Type header.

func (*Response) SetHTML

func (resp *Response) SetHTML(html string)

SetHTML sets response body as HTML and sets appropriate Content-Type.

func (*Response) SetJSON

func (resp *Response) SetJSON(data any) error

SetJSON sets response body as JSON and sets appropriate Content-Type.

func (*Response) SetStatusCode

func (resp *Response) SetStatusCode(statusCode int)

SetStatusCode sets response status code.

func (*Response) SetText

func (resp *Response) SetText(text string)

SetText sets response body as plain text and sets appropriate Content-Type.

func (*Response) StatusCode

func (resp *Response) StatusCode() int

StatusCode returns response status code.

func (*Response) Write

func (resp *Response) Write(w metanet.Conn) error

Write writes response to writer.

func (*Response) WriteDeflate

func (resp *Response) WriteDeflate(p []byte) (int, error)

WriteDeflate writes deflated response body.

func (*Response) WriteDeflateLevel

func (resp *Response) WriteDeflateLevel(p []byte, level int) (int, error)

WriteDeflateLevel writes deflated response body with specified compression level.

func (*Response) WriteGzip

func (resp *Response) WriteGzip(p []byte) (int, error)

WriteGzip writes gzipped response body.

func (*Response) WriteGzipLevel

func (resp *Response) WriteGzipLevel(p []byte, level int) (int, error)

WriteGzipLevel writes gzipped response body with specified compression level.

func (*Response) WriteZstd

func (resp *Response) WriteZstd(p []byte) (int, error)

WriteZstd writes zstd compressed response body.

func (*Response) WriteZstdLevel

func (resp *Response) WriteZstdLevel(p []byte, level int) (int, error)

WriteZstdLevel writes zstd compressed response body with specified compression level.

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, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value, while Set-Cookie will not clear previous cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked response body.

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, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value, while Set-Cookie will not clear previous cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked response body.

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, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value, while the Set-Cookie header will not clear previous cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked response body.

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, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value, while Set-Cookie will not clear previous cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked response body.

func (*ResponseHeader) AddTrailer

func (h *ResponseHeader) AddTrailer(trailer string) error

AddTrailer add Trailer header value for chunked response to indicate which headers will be sent after the body.

Use Set to set the trailer header later.

Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages.

The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)

Return ErrBadTrailer if contain any forbidden trailers.

func (*ResponseHeader) AddTrailerBytes

func (h *ResponseHeader) AddTrailerBytes(trailer []byte) (err error)

AddTrailerBytes add Trailer header value for chunked response to indicate which headers will be sent after the body.

Use Set to set the trailer header later.

Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages.

The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)

Return ErrBadTrailer if contain any forbidden trailers.

func (*ResponseHeader) All

func (h *ResponseHeader) All() iter.Seq2[[]byte, []byte]

All returns an iterator over key-value pairs in h.

The key and value may invalid outside the iteration loop. Copy key and/or value contents for each iteration if you need retaining them.

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

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

ContentEncoding returns Content-Encoding header value.

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

func (h *ResponseHeader) Cookies() iter.Seq2[[]byte, []byte]

Cookies returns an iterator over key-value paired response cookie in h.

Cookie name is passed in key and the whole Set-Cookie header value is passed in value for each iteration. Value may be parsed with Cookie.ParseBytes().

The key and value may invalid outside the iteration loop. Copy key and/or value contents for each iteration if you need retaining them.

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.

Headers that set as Trailer will not represent. Use TrailerHeader for trailers.

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 header 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) PeekAll

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

PeekAll returns all header value for the given key.

The returned value is valid until the request is released, either though ReleaseResponse or your request handler returning. Any future calls to the Peek* will modify the returned value. Do not store references to 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) PeekKeys

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

PeekKeys return all header keys.

The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Any future calls to the Peek* will modify the returned value. Do not store references to returned value. Make copies instead.

func (*ResponseHeader) PeekTrailerKeys

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

PeekTrailerKeys return all trailer keys.

The returned value is valid until the request is released, either though ReleaseResponse or your request handler returning. Any future calls to the Peek* will modify the returned value. Do not store references to returned value. Make copies instead.

func (*ResponseHeader) Protocol

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

Protocol returns HTTP protocol.

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

func (h *ResponseHeader) ReadTrailer(r *bufio.Reader) error

ReadTrailer reads response trailer header from r.

io.EOF is returned if r is closed before reading the first 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.

Please note that the Set-Cookie header will not clear previous cookies, use SetCookie instead to reset cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked response body.

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.

Please note that the Set-Cookie header will not clear previous cookies, use SetCookie instead to reset cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked response body.

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.

Please note that the Set-Cookie header will not clear previous cookies, use SetCookie instead to reset cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked response body.

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.

Please note that the Set-Cookie header will not clear previous cookies, use SetCookie instead to reset cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked response body.

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.

Please note that the Set-Cookie header will not clear previous cookies, use SetCookie instead to reset cookies.

If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked response body.

func (*ResponseHeader) SetConnectionClose

func (h *ResponseHeader) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*ResponseHeader) SetContentEncoding

func (h *ResponseHeader) SetContentEncoding(contentEncoding string)

SetContentEncoding sets Content-Encoding header value.

func (*ResponseHeader) SetContentEncodingBytes

func (h *ResponseHeader) SetContentEncodingBytes(contentEncoding []byte)

SetContentEncodingBytes sets Content-Encoding header value.

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 safe 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) SetNonSpecial

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

SetNonSpecial directly put into map i.e. not a basic header.

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

func (h *ResponseHeader) SetTrailer(trailer string) error

SetTrailer sets header Trailer value for chunked response to indicate which headers will be sent after the body.

Use Set to set the trailer header later.

Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages.

The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)

Return ErrBadTrailer if contain any forbidden trailers.

func (*ResponseHeader) SetTrailerBytes

func (h *ResponseHeader) SetTrailerBytes(trailer []byte) error

SetTrailerBytes sets Trailer header value for chunked response to indicate which headers will be sent after the body.

Use Set to set the trailer header later.

Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages.

The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)

Return ErrBadTrailer if contain any forbidden trailers.

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

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

TrailerHeader returns response trailer header representation.

Trailers will only be received with chunked transfer.

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

func (h *ResponseHeader) Trailers() iter.Seq[[]byte]

Trailers returns an iterator over trailers in h.

The value of trailer may invalid outside the iteration loop.

func (*ResponseHeader) VisitAll deprecated

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.

Deprecated: Use All instead.

func (*ResponseHeader) VisitAllCookie deprecated

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.

Deprecated: Use Cookies instead.

func (*ResponseHeader) VisitAllTrailer deprecated

func (h *ResponseHeader) VisitAllTrailer(f func(value []byte))

VisitAllTrailer calls f for each response Trailer.

f must not retain references to value after returning.

Deprecated: Use Trailers instead.

func (*ResponseHeader) Write

func (h *ResponseHeader) Write(w metanet.Conn) 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 RouteGroup

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

RouteGroup represents a group of routes.

func (*RouteGroup) Any

func (g *RouteGroup) Any(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Any adds route for all HTTP methods to group.

func (*RouteGroup) DELETE

func (g *RouteGroup) DELETE(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

DELETE adds DELETE route to group.

func (*RouteGroup) GET

func (g *RouteGroup) GET(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

GET adds GET route to group.

func (*RouteGroup) Group

func (g *RouteGroup) Group(prefix string, middlewares ...MiddlewareFunc) *RouteGroup

Group creates a sub route group.

func (*RouteGroup) HEAD

func (g *RouteGroup) HEAD(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

HEAD adds HEAD route to group.

func (*RouteGroup) OPTIONS

func (g *RouteGroup) OPTIONS(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

OPTIONS adds OPTIONS route to group.

func (*RouteGroup) PATCH

func (g *RouteGroup) PATCH(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

PATCH adds PATCH route to group.

func (*RouteGroup) POST

func (g *RouteGroup) POST(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

POST adds POST route to group.

func (*RouteGroup) PUT

func (g *RouteGroup) PUT(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

PUT adds PUT route to group.

func (*RouteGroup) Use

func (g *RouteGroup) Use(middlewares ...MiddlewareFunc)

Use adds middleware to route group.

type Router

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

Router represents HTTP router using Gin's radix tree algorithm.

func NewRouter

func NewRouter() *Router

NewRouter creates a new router.

func (*Router) Any

func (r *Router) Any(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Any adds route for all HTTP methods.

func (*Router) DELETE

func (r *Router) DELETE(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

DELETE adds DELETE route.

func (*Router) GET

func (r *Router) GET(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

GET adds GET route.

func (*Router) Group

func (r *Router) Group(prefix string, middlewares ...MiddlewareFunc) *RouteGroup

Group creates a route group.

func (*Router) HEAD

func (r *Router) HEAD(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

HEAD adds HEAD route.

func (*Router) Handle

func (r *Router) Handle(ctx *Context)

Handle handles HTTP request using Gin's radix tree algorithm.

func (*Router) NotFound

func (r *Router) NotFound(handler HandlerFunc)

NotFound sets not found handler.

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

OPTIONS adds OPTIONS route.

func (*Router) PATCH

func (r *Router) PATCH(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

PATCH adds PATCH route.

func (*Router) POST

func (r *Router) POST(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

POST adds POST route.

func (*Router) PUT

func (r *Router) PUT(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

PUT adds PUT route.

func (*Router) Use

func (r *Router) Use(middlewares ...MiddlewareFunc)

Use adds middleware to router.

type StreamWriter

type StreamWriter func(w *bufio.Writer)

StreamWriter must write data to w.

Usually StreamWriter writes data to w in a loop (aka 'data streaming').

StreamWriter must return immediately if w returns error.

Since the written data is buffered, do not forget calling w.Flush when the data must be propagated to reader.

type URI

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.

type Writer

type Writer interface {
	Write(p []byte) (int, error)
	Flush() error
	Close() error
	Reset(w io.Writer)
}

Writer is an interface stackless writer must conform to.

The interface contains common subset for Writers from compress/* packages.

func NewWriter

func NewWriter(dstW io.Writer, newWriter NewWriterFunc) Writer

NewWriter creates a stackless writer around a writer returned from newWriter.

The returned writer writes data to dstW.

Writers that use a lot of stack space may be wrapped into stackless writer, thus saving stack space for high number of concurrently running goroutines.

Jump to

Keyboard shortcuts

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