Documentation ¶
Overview ¶
Package fasthttp provides fast HTTP server and client API.
Fasthttp provides the following features:
Optimized for speed. Easily handles more than 100K qps and more than 1M concurrent keep-alive connections on modern hardware.
Optimized for low memory usage.
Easy 'Connection: Upgrade' support via RequestCtx.Hijack.
Server provides the following anti-DoS limits:
- The number of concurrent connections.
- The number of concurrent connections per client IP.
- The number of requests per connection.
- Request read timeout.
- Response write timeout.
- Maximum request header size.
- Maximum request body size.
- Maximum request execution time.
- Maximum keep-alive connection lifetime.
- Early filtering out non-GET requests.
A lot of additional useful info is exposed to request handler:
- Server and client address.
- Per-request logger.
- Unique request id.
- Request start time.
- Connection start time.
- Request sequence number for the current connection.
Client supports automatic retry on idempotent requests' failure.
Fasthttp API is designed with the ability to extend existing client and server implementations or to write custom client and server implementations from scratch.
SPDX-License-Identifier: MIT SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
Copied from https://github.com/labstack/echo/blob/master/bind.go (The difference is in fallback tag name to field name and skip bind by hyphen) See license https://github.com/labstack/echo/blob/master/LICENSE
⚡️ Fiber is an Express inspired web framework written in Go with ☕️ 🤖 Github Repository: https://github.com/gofiber/fiber 📌 API Documentation: https://docs.gofiber.io
Package fiber is an Express inspired web framework built on top of Fasthttp, the fastest HTTP engine for Go. Designed to ease things up for fast development with zero memory allocation and performance in mind.
Copied from https://github.com/gofiber/fiber See license https://github.com/gofiber/fiber/blob/main/LICENSE
Copied from https://github.com/gofiber/template See license https://github.com/gofiber/template/blob/master/LICENSE
Index ¶
- Constants
- Variables
- func AcquireTimer(timeout time.Duration) *time.Timer
- func AddMissingPort(addr string, isTLS bool) string
- func AppendDeflateBytes(dst, src []byte) []byte
- func AppendDeflateBytesLevel(dst, src []byte, level int) []byte
- func AppendGunzipBytes(dst, src []byte) ([]byte, error)
- func AppendGzipBytes(dst, src []byte) []byte
- func AppendGzipBytesLevel(dst, src []byte, level int) []byte
- func AppendHTMLEscape(dst []byte, s string) []byte
- func AppendHTMLEscapeBytes(dst, s []byte) []byte
- func AppendHTTPDate(dst []byte, date time.Time) []byte
- func AppendIPv4(dst []byte, ip net.IP) []byte
- func AppendInflateBytes(dst, src []byte) ([]byte, error)
- func AppendNormalizedHeaderKey(dst []byte, key string) []byte
- func AppendNormalizedHeaderKeyBytes(dst, key []byte) []byte
- func AppendQuotedArg(dst, src []byte) []byte
- func AppendUint(dst []byte, n int) []byte
- func AppendUnquotedArg(dst, src []byte) []byte
- func B2S(b []byte) string
- func CleanPath(p string) string
- func CoarseTimeNow() time.Timedeprecated
- func CopyBytes(b []byte) []byte
- func CopyString(s string) string
- func Dial(addr string) (net.Conn, error)
- func DialDualStack(addr string) (net.Conn, error)
- func DialDualStackTimeout(addr string, timeout time.Duration) (net.Conn, error)
- func DialTimeout(addr string, timeout time.Duration) (net.Conn, error)
- func Do(req *Request, resp *Response) error
- func DoDeadline(req *Request, resp *Response, deadline time.Time) error
- func DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error
- func DoTimeout(req *Request, resp *Response, timeout time.Duration) error
- func FileLastModified(path string) (time.Time, error)
- func GenerateTestCertificate(host string) ([]byte, []byte, error)
- func Get(dst []byte, url string) (statusCode int, body []byte, err error)
- func GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error)
- func GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error)
- func ListenAndServe(addr string, handler RequestHandler) error
- func ListenAndServeUNIX(addr string, mode os.FileMode, handler RequestHandler) error
- func NewStreamReader(sw StreamWriter) io.ReadCloser
- func ParseByteRange(byteRange []byte, contentLength int) (startPos, endPos int, err error)
- func ParseHTTPDate(date []byte) (time.Time, error)
- func ParseIPv4(dst net.IP, ipStr []byte) (net.IP, error)
- func ParseUfloat(buf []byte) (float64, error)
- func ParseUint(buf []byte) (int, error)
- func Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error)
- func ReleaseArgs(a *Args)
- func ReleaseCookie(c *Cookie)
- func ReleaseRequest(req *Request)
- func ReleaseResponse(resp *Response)
- func ReleaseTimer(t *time.Timer)
- func ReleaseURI(u *URI)
- func S2B(s string) []byte
- func SaveMultipartFile(fh *multipart.FileHeader, path string) (err error)
- func Serve(ln net.Listener, handler RequestHandler) error
- func ServeConn(c net.Conn, handler RequestHandler) error
- func ServeFS(ctx *RequestCtx, filesystem fs.FS, path string)
- func ServeFile(ctx *RequestCtx, path string)
- func ServeFileBytes(ctx *RequestCtx, path []byte)
- func ServeFileBytesUncompressed(ctx *RequestCtx, path []byte)
- func ServeFileUncompressed(ctx *RequestCtx, path string)
- func SetBodySizePoolLimit(reqBodyLimit, respBodyLimit int)
- func StatusCodeIsRedirect(statusCode int) bool
- func StatusMessage(statusCode int) string
- func VisitHeaderParams(b []byte, f func(key, value []byte) bool)
- func WriteDeflate(w io.Writer, p []byte) (int, error)
- func WriteDeflateLevel(w io.Writer, p []byte, level int) (int, error)
- func WriteGunzip(w io.Writer, p []byte) (int, error)
- func WriteGzip(w io.Writer, p []byte) (int, error)
- func WriteGzipLevel(w io.Writer, p []byte, level int) (int, error)
- func WriteInflate(w io.Writer, p []byte) (int, error)
- func WriteMultipartForm(w io.Writer, f *multipart.Form, boundary string) error
- type App
- func (app *App) GetPost(path string, handle Handle) *Router
- func (app *App) Group(prefix string) *Group
- func (app *App) Handler(c *Ctx)
- func (app *App) Serve(addr string) error
- func (app *App) ServeUnix(path string) error
- func (app *App) ServerHandler(reset ...bool) *Server
- func (app *App) Use(handle Handle)
- type Args
- func (a *Args) Add(key, value string)
- func (a *Args) AddBytesK(key []byte, value string)
- func (a *Args) AddBytesKNoValue(key []byte)
- func (a *Args) AddBytesKV(key, value []byte)
- func (a *Args) AddBytesV(key string, value []byte)
- func (a *Args) AddNoValue(key string)
- func (a *Args) AppendBytes(dst []byte) []byte
- func (a *Args) CopyTo(dst *Args)
- func (a *Args) Del(key string)
- func (a *Args) DelBytes(key []byte)
- func (a *Args) GetBool(key string) bool
- func (a *Args) GetUfloat(key string) (float64, error)
- func (a *Args) GetUfloatOrZero(key string) float64
- func (a *Args) GetUint(key string) (int, error)
- func (a *Args) GetUintOrZero(key string) int
- func (a *Args) Has(key string) bool
- func (a *Args) HasBytes(key []byte) bool
- func (a *Args) Len() int
- func (a *Args) Parse(s string)
- func (a *Args) ParseBytes(b []byte)
- func (a *Args) Peek(key string) []byte
- func (a *Args) PeekBytes(key []byte) []byte
- func (a *Args) PeekMulti(key string) [][]byte
- func (a *Args) PeekMultiBytes(key []byte) [][]byte
- func (a *Args) QueryString() []byte
- func (a *Args) Reset()
- func (a *Args) Set(key, value string)
- func (a *Args) SetBytesK(key []byte, value string)
- func (a *Args) SetBytesKNoValue(key []byte)
- func (a *Args) SetBytesKV(key, value []byte)
- func (a *Args) SetBytesV(key string, value []byte)
- func (a *Args) SetNoValue(key string)
- func (a *Args) SetUint(key string, value int)
- func (a *Args) SetUintBytes(key []byte, value int)
- func (a *Args) Sort(f func(x, y []byte) int)
- func (a *Args) String() string
- func (a *Args) VisitAll(f func(key, value []byte))
- func (a *Args) WriteTo(w io.Writer) (int64, error)
- type BalancingClient
- type Binder
- type CacheKind
- type Client
- func (c *Client) CloseIdleConnections()
- func (c *Client) Do(req *Request, resp *Response) error
- func (c *Client) DoDeadline(req *Request, resp *Response, deadline time.Time) error
- func (c *Client) DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error
- func (c *Client) DoTimeout(req *Request, resp *Response, timeout time.Duration) error
- func (c *Client) Get(dst []byte, url string) (statusCode int, body []byte, err error)
- func (c *Client) GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error)
- func (c *Client) GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error)
- func (c *Client) Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error)
- type ConnPoolStrategyType
- type ConnState
- type Cookie
- func (c *Cookie) AppendBytes(dst []byte) []byte
- func (c *Cookie) Cookie() []byte
- func (c *Cookie) CopyTo(src *Cookie)
- func (c *Cookie) Domain() []byte
- func (c *Cookie) Expire() time.Time
- func (c *Cookie) HTTPOnly() bool
- func (c *Cookie) Key() []byte
- func (c *Cookie) MaxAge() int
- func (c *Cookie) Parse(src string) error
- func (c *Cookie) ParseBytes(src []byte) error
- func (c *Cookie) Partitioned() bool
- func (c *Cookie) Path() []byte
- func (c *Cookie) Reset()
- func (c *Cookie) SameSite() CookieSameSite
- func (c *Cookie) Secure() bool
- func (c *Cookie) SetDomain(domain string)
- func (c *Cookie) SetDomainBytes(domain []byte)
- func (c *Cookie) SetExpire(expire time.Time)
- func (c *Cookie) SetHTTPOnly(httpOnly bool)
- func (c *Cookie) SetKey(key string)
- func (c *Cookie) SetKeyBytes(key []byte)
- func (c *Cookie) SetMaxAge(seconds int)
- func (c *Cookie) SetPartitioned(partitioned bool)
- func (c *Cookie) SetPath(path string)
- func (c *Cookie) SetPathBytes(path []byte)
- func (c *Cookie) SetSameSite(mode CookieSameSite)
- func (c *Cookie) SetSecure(secure bool)
- func (c *Cookie) SetValue(value string)
- func (c *Cookie) SetValueBytes(value []byte)
- func (c *Cookie) String() string
- func (c *Cookie) Value() []byte
- func (c *Cookie) WriteTo(w io.Writer) (int64, error)
- type CookieSameSite
- type Cookiex
- type Ctx
- func (c *Ctx) Accepts(offers ...string) string
- func (c *Ctx) AllParams() map[string]string
- func (c *Ctx) Append(field string, values ...string)
- func (c *Ctx) Attachment(filename ...string)
- func (c *Ctx) BaseURL() string
- func (c *Ctx) Bind(vars Map) error
- func (c *Ctx) Body() []byte
- func (c *Ctx) BodyParser(out any) error
- func (c *Ctx) BodyRaw() []byte
- func (c *Ctx) ClearCookie(key ...string)
- func (c *Ctx) ClientHelloInfo() *tls.ClientHelloInfo
- func (c *Ctx) Cookie(cookie *Cookiex, secureCheck ...bool)
- func (c *Ctx) CookieParser(out any) error
- func (c *Ctx) Cookies(key string, defaultValue ...string) string
- func (c *Ctx) Download(file string, filename ...string) error
- func (c *Ctx) Finish() error
- func (c *Ctx) FormParams() map[string][]string
- func (c *Ctx) FormValues(key string, defaultValue ...string) string
- func (c *Ctx) Format(body any) error
- func (c *Ctx) Get(key string, defaultValue ...string) string
- func (c *Ctx) GetReqHeaders() map[string][]string
- func (c *Ctx) GetRespHeader(key string, defaultValue ...string) string
- func (c *Ctx) GetRespHeaders() map[string][]string
- func (c *Ctx) GetRouteURL(routeName string, params Map) (string, error)
- func (c *Ctx) Hostname() string
- func (c *Ctx) IP() string
- func (c *Ctx) IPs() (ips []string)
- func (c *Ctx) Is(extension string) bool
- func (c *Ctx) IsFromLocal() bool
- func (c *Ctx) IsProxyTrusted() bool
- func (c *Ctx) JSON(data any, ctype ...string) error
- func (c *Ctx) JSONP(data any, callback ...string) error
- func (c *Ctx) Links(link ...string)
- func (c *Ctx) Locals(key any, value ...any) any
- func (c *Ctx) Location(path string)
- func (c *Ctx) Methods() string
- func (c *Ctx) Next() error
- func (c *Ctx) OriginalURL() string
- func (c *Ctx) Params(key string, defaultValue ...string) (v string)
- func (c *Ctx) ParamsInt(key string, defaultValue ...int) (int, error)
- func (c *Ctx) ParamsParser(out any) error
- func (c *Ctx) Paths() string
- func (c *Ctx) Port() string
- func (c *Ctx) Queries() map[string]string
- func (c *Ctx) Query(key string, defaultValue ...string) string
- func (c *Ctx) QueryBool(key string, defaultValue ...bool) bool
- func (c *Ctx) QueryFloat(key string, defaultValue ...float64) float64
- func (c *Ctx) QueryInt(key string, defaultValue ...int) int
- func (c *Ctx) QueryParser(out any) error
- func (c *Ctx) Range(size int) (Range, error)
- func (c *Ctx) RedirectBack(fallback string, status ...int) error
- func (c *Ctx) RedirectToRoute(routeName string, params Map, status ...int) error
- func (c *Ctx) Redirects(location string, status ...int) error
- func (c *Ctx) Render(name string, bind Map, layouts ...string) error
- func (c *Ctx) ReqHeaderParser(out any) error
- func (c *Ctx) Route() string
- func (c *Ctx) RoutePath() string
- func (*Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error
- func (c *Ctx) Scheme() string
- func (c *Ctx) Secure() bool
- func (c *Ctx) Send(body []byte) error
- func (c *Ctx) SendError(err *Error)
- func (c *Ctx) SendStatus(status int) error
- func (c *Ctx) SendStream(stream io.Reader, size ...int) error
- func (c *Ctx) SendString(body string) error
- func (c *Ctx) Served() bool
- func (c *Ctx) Server() *Server
- func (c *Ctx) Set(key, val string)
- func (c *Ctx) SetUserContext(ctx context.Context)
- func (c *Ctx) SetUserValues(vals Map)
- func (c *Ctx) Status(status int) *Ctx
- func (c *Ctx) Subdomains(offset ...int) []string
- func (c *Ctx) Type(extension string, charset ...string) *Ctx
- func (c *Ctx) UserContext() context.Context
- func (c *Ctx) Vary(fields ...string)
- func (c *Ctx) Writef(f string, a ...any) (int, error)
- func (c *Ctx) XHR() bool
- func (c *Ctx) XML(data any) error
- type DialFunc
- type DialFuncWithTimeout
- type ErrBodyStreamWritePanic
- type ErrBrokenChunk
- type ErrNothingRead
- type ErrSmallBuffer
- type Error
- type ErrorHandler
- type EscapeError
- type FS
- type FormValueFunc
- type Group
- func (r *Group) Delete(path string, handle Handle) *Router
- func (r *Group) Get(path string, handle Handle) *Router
- func (r *Group) GetPost(path string, handle Handle) *Router
- func (r *Group) Group(prefix string) *Group
- func (r *Group) Handle(method, path string, handle Handle) *Router
- func (r *Group) Head(path string, handle Handle) *Router
- func (r *Group) Options(path string, handle Handle) *Router
- func (r *Group) Patch(path string, handle Handle) *Router
- func (r *Group) Post(path string, handle Handle) *Router
- func (r *Group) Put(path string, handle Handle) *Router
- func (r *Group) Use(handle Handle)
- type Handle
- type HijackHandler
- type HostClient
- func (c *HostClient) CloseIdleConnections()
- func (c *HostClient) ConnsCount() int
- func (c *HostClient) Do(req *Request, resp *Response) error
- func (c *HostClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error
- func (c *HostClient) DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error
- func (c *HostClient) DoTimeout(req *Request, resp *Response, timeout time.Duration) error
- func (c *HostClient) Get(dst []byte, url string) (statusCode int, body []byte, err error)
- func (c *HostClient) GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error)
- func (c *HostClient) GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error)
- func (c *HostClient) LastUseTime() time.Time
- func (c *HostClient) PendingRequests() int
- func (c *HostClient) Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error)
- func (c *HostClient) SetMaxConns(newMaxConns int)
- type InvalidHostError
- type LBClient
- func (cc *LBClient) AddClient(c BalancingClient) int
- func (cc *LBClient) Do(req *Request, resp *Response) error
- func (cc *LBClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error
- func (cc *LBClient) DoTimeout(req *Request, resp *Response, timeout time.Duration) error
- func (cc *LBClient) RemoveClients(rc func(BalancingClient) bool) int
- type Logger
- type Map
- type Param
- type Params
- type PathRewriteFunc
- type PipelineClient
- type Range
- type RangeSet
- type ReadCloserWithError
- type Render
- func (r *Render) AddFunc(f string, fn any) *Render
- func (r *Render) EmbedFS(fs *embed.FS) *Render
- func (r *Render) Load() *Render
- func (r *Render) Render(out io.Writer, name string, binding Map, layouts ...string) (err error)
- func (r *Render) RenderBytes(name string, binding Map, layout ...string) ([]byte, error)
- type Request
- func (req *Request) AppendBody(p []byte)
- func (req *Request) AppendBodyString(s string)
- func (req *Request) Body() []byte
- func (req *Request) BodyGunzip() ([]byte, error)
- func (req *Request) BodyInflate() ([]byte, error)
- func (req *Request) BodyStream() io.Reader
- func (req *Request) BodyUncompressed() ([]byte, error)
- func (req *Request) BodyWriteTo(w io.Writer) error
- func (req *Request) BodyWriter() io.Writer
- func (req *Request) CloseBodyStream() error
- func (req *Request) ConnectionClose() bool
- func (req *Request) ContinueReadBody(r *bufio.Reader, maxBodySize int, preParseMultipartForm ...bool) error
- func (req *Request) ContinueReadBodyStream(r *bufio.Reader, maxBodySize int, preParseMultipartForm ...bool) error
- func (req *Request) CopyTo(dst *Request)
- func (req *Request) Host() []byte
- func (req *Request) IsBodyStream() bool
- func (req *Request) MayContinue() bool
- func (req *Request) MultipartForm() (*multipart.Form, error)
- func (req *Request) PostArgs() *Args
- func (req *Request) Read(r *bufio.Reader) error
- func (req *Request) ReadBody(r *bufio.Reader, contentLength, maxBodySize int) (err error)
- func (req *Request) ReadLimitBody(r *bufio.Reader, maxBodySize int) error
- func (req *Request) ReleaseBody(size int)
- func (req *Request) RemoveMultipartFormFiles()
- func (req *Request) RequestURI() []byte
- func (req *Request) Reset()
- func (req *Request) ResetBody()
- func (req *Request) SetBody(body []byte)
- func (req *Request) SetBodyRaw(body []byte)
- func (req *Request) SetBodyStream(bodyStream io.Reader, bodySize int)
- func (req *Request) SetBodyStreamWriter(sw StreamWriter)
- func (req *Request) SetBodyString(body string)
- func (req *Request) SetConnectionClose()
- func (req *Request) SetHost(host string)
- func (req *Request) SetHostBytes(host []byte)
- func (req *Request) SetRequestURI(requestURI string)
- func (req *Request) SetRequestURIBytes(requestURI []byte)
- func (req *Request) SetTimeout(t time.Duration)
- func (req *Request) SetURI(newURI *URI)
- func (req *Request) String() string
- func (req *Request) SwapBody(body []byte) []byte
- func (req *Request) URI() *URI
- func (req *Request) Write(w *bufio.Writer) error
- func (req *Request) WriteTo(w io.Writer) (int64, error)
- type RequestConfig
- type RequestCtx
- func (ctx *RequestCtx) Conn() net.Conn
- func (ctx *RequestCtx) ConnID() uint64
- func (ctx *RequestCtx) ConnRequestNum() uint64
- func (ctx *RequestCtx) ConnTime() time.Time
- func (ctx *RequestCtx) Deadline() (deadline time.Time, ok bool)
- func (ctx *RequestCtx) Done() <-chan struct{}
- func (ctx *RequestCtx) Err() error
- func (ctx *RequestCtx) Error(msg string, statusCode int)
- func (ctx *RequestCtx) FormFile(key string) (*multipart.FileHeader, error)
- func (ctx *RequestCtx) FormValue(key string) []byte
- func (ctx *RequestCtx) Hijack(handler HijackHandler)
- func (ctx *RequestCtx) HijackSetNoResponse(noResponse bool)
- func (ctx *RequestCtx) Hijacked() bool
- func (ctx *RequestCtx) Host() []byte
- func (ctx *RequestCtx) ID() uint64
- func (ctx *RequestCtx) IfModifiedSince(lastModified time.Time) bool
- func (ctx *RequestCtx) Init(req *Request, remoteAddr net.Addr, logger Logger)
- func (ctx *RequestCtx) Init2(conn net.Conn, logger Logger, reduceMemoryUsage bool)
- func (ctx *RequestCtx) IsBodyStream() bool
- func (ctx *RequestCtx) IsConnect() bool
- func (ctx *RequestCtx) IsDelete() bool
- func (ctx *RequestCtx) IsGet() bool
- func (ctx *RequestCtx) IsHead() bool
- func (ctx *RequestCtx) IsOptions() bool
- func (ctx *RequestCtx) IsPatch() bool
- func (ctx *RequestCtx) IsPost() bool
- func (ctx *RequestCtx) IsPut() bool
- func (ctx *RequestCtx) IsTLS() bool
- func (ctx *RequestCtx) IsTrace() bool
- func (ctx *RequestCtx) LastTimeoutErrorResponse() *Response
- func (ctx *RequestCtx) LocalAddr() net.Addr
- func (ctx *RequestCtx) LocalIP() net.IP
- func (ctx *RequestCtx) Logger() Logger
- func (ctx *RequestCtx) Method() []byte
- func (ctx *RequestCtx) MultipartForm() (*multipart.Form, error)
- func (ctx *RequestCtx) NotFound()
- func (ctx *RequestCtx) NotModified()
- func (ctx *RequestCtx) Path() []byte
- func (ctx *RequestCtx) PostArgs() *Args
- func (ctx *RequestCtx) PostBody() []byte
- func (ctx *RequestCtx) QueryArgs() *Args
- func (ctx *RequestCtx) Redirect(uri string, statusCode int)
- func (ctx *RequestCtx) RedirectBytes(uri []byte, statusCode int)
- func (ctx *RequestCtx) Referer() []byte
- func (ctx *RequestCtx) RemoteAddr() net.Addr
- func (ctx *RequestCtx) RemoteIP() net.IP
- func (ctx *RequestCtx) RemoveUserValue(key any)
- func (ctx *RequestCtx) RemoveUserValueBytes(key []byte)
- func (ctx *RequestCtx) RequestBodyStream() io.Reader
- func (ctx *RequestCtx) RequestURI() []byte
- func (ctx *RequestCtx) ResetBody()
- func (ctx *RequestCtx) ResetUserValues()
- func (ctx *RequestCtx) SendFile(path string)
- func (ctx *RequestCtx) SendFileBytes(path []byte)
- func (ctx *RequestCtx) SetBody(body []byte)
- func (ctx *RequestCtx) SetBodyStream(bodyStream io.Reader, bodySize int)
- func (ctx *RequestCtx) SetBodyStreamWriter(sw StreamWriter)
- func (ctx *RequestCtx) SetBodyString(body string)
- func (ctx *RequestCtx) SetConnectionClose()
- func (ctx *RequestCtx) SetContentType(contentType string)
- func (ctx *RequestCtx) SetContentTypeBytes(contentType []byte)
- func (ctx *RequestCtx) SetRemoteAddr(remoteAddr net.Addr)
- func (ctx *RequestCtx) SetStatusCode(statusCode int)
- func (ctx *RequestCtx) SetUserValue(key, value any)
- func (ctx *RequestCtx) SetUserValueBytes(key []byte, value any)
- func (ctx *RequestCtx) String() string
- func (ctx *RequestCtx) Success(contentType string, body []byte)
- func (ctx *RequestCtx) SuccessString(contentType, body string)
- func (ctx *RequestCtx) TLSConnectionState() *tls.ConnectionState
- func (ctx *RequestCtx) Time() time.Time
- func (ctx *RequestCtx) TimeoutError(msg string)
- func (ctx *RequestCtx) TimeoutErrorWithCode(msg string, statusCode int)
- func (ctx *RequestCtx) TimeoutErrorWithResponse(resp *Response)
- func (ctx *RequestCtx) URI() *URI
- func (ctx *RequestCtx) UserAgent() []byte
- func (ctx *RequestCtx) UserValue(key any) any
- func (ctx *RequestCtx) UserValueBytes(key []byte) any
- func (ctx *RequestCtx) Value(key any) any
- func (ctx *RequestCtx) VisitUserValues(visitor func([]byte, any))
- func (ctx *RequestCtx) VisitUserValuesAll(visitor func(any, any))
- func (ctx *RequestCtx) Write(p []byte) (int, error)
- func (ctx *RequestCtx) WriteString(s string) (int, error)
- type RequestHandler
- type RequestHeader
- func (h *RequestHeader) Add(key, value string)
- func (h *RequestHeader) AddBytesK(key []byte, value string)
- func (h *RequestHeader) AddBytesKV(key, value []byte)
- func (h *RequestHeader) AddBytesV(key string, value []byte)
- func (h *RequestHeader) AddTrailer(trailer string) error
- func (h *RequestHeader) AddTrailerBytes(trailer []byte) error
- func (h *RequestHeader) AppendBytes(dst []byte) []byte
- func (h *RequestHeader) ConnectionClose() bool
- func (h *RequestHeader) ConnectionUpgrade() bool
- func (h *RequestHeader) ContentEncoding() []byte
- func (h *RequestHeader) ContentLength() int
- func (h *RequestHeader) ContentType() []byte
- func (h *RequestHeader) Cookie(key string) []byte
- func (h *RequestHeader) CookieBytes(key []byte) []byte
- func (h *RequestHeader) CopyTo(dst *RequestHeader)
- func (h *RequestHeader) Del(key string)
- func (h *RequestHeader) DelAllCookies()
- func (h *RequestHeader) DelBytes(key []byte)
- func (h *RequestHeader) DelCookie(key string)
- func (h *RequestHeader) DelCookieBytes(key []byte)
- func (h *RequestHeader) DisableNormalizing()
- func (h *RequestHeader) DisableSpecialHeader()
- func (h *RequestHeader) EnableNormalizing()
- func (h *RequestHeader) EnableSpecialHeader()
- func (h *RequestHeader) HasAcceptEncoding(acceptEncoding string) bool
- func (h *RequestHeader) HasAcceptEncodingBytes(acceptEncoding []byte) bool
- func (h *RequestHeader) Header() []byte
- func (h *RequestHeader) Host() []byte
- func (h *RequestHeader) IsConnect() bool
- func (h *RequestHeader) IsDelete() bool
- func (h *RequestHeader) IsGet() bool
- func (h *RequestHeader) IsHTTP11() bool
- func (h *RequestHeader) IsHead() bool
- func (h *RequestHeader) IsOptions() bool
- func (h *RequestHeader) IsPatch() bool
- func (h *RequestHeader) IsPost() bool
- func (h *RequestHeader) IsPut() bool
- func (h *RequestHeader) IsTrace() bool
- func (h *RequestHeader) Len() int
- func (h *RequestHeader) Method() []byte
- func (h *RequestHeader) MultipartFormBoundary() []byte
- func (h *RequestHeader) Peek(key string) []byte
- func (h *RequestHeader) PeekAll(key string) [][]byte
- func (h *RequestHeader) PeekBytes(key []byte) []byte
- func (h *RequestHeader) PeekKeys() [][]byte
- func (h *RequestHeader) PeekTrailerKeys() [][]byte
- func (h *RequestHeader) Protocol() []byte
- func (h *RequestHeader) RawHeaders() []byte
- func (h *RequestHeader) Read(r *bufio.Reader) error
- func (h *RequestHeader) ReadTrailer(r *bufio.Reader) error
- func (h *RequestHeader) Referer() []byte
- func (h *RequestHeader) RequestURI() []byte
- func (h *RequestHeader) Reset()
- func (h *RequestHeader) ResetConnectionClose()
- func (h *RequestHeader) Set(key, value string)
- func (h *RequestHeader) SetByteRange(startPos, endPos int)
- func (h *RequestHeader) SetBytesK(key []byte, value string)
- func (h *RequestHeader) SetBytesKV(key, value []byte)
- func (h *RequestHeader) SetBytesV(key string, value []byte)
- func (h *RequestHeader) SetCanonical(key, value []byte)
- func (h *RequestHeader) SetConnectionClose()
- func (h *RequestHeader) SetContentEncoding(contentEncoding string)
- func (h *RequestHeader) SetContentEncodingBytes(contentEncoding []byte)
- func (h *RequestHeader) SetContentLength(contentLength int)
- func (h *RequestHeader) SetContentType(contentType string)
- func (h *RequestHeader) SetContentTypeBytes(contentType []byte)
- func (h *RequestHeader) SetCookie(key, value string)
- func (h *RequestHeader) SetCookieBytesK(key []byte, value string)
- func (h *RequestHeader) SetCookieBytesKV(key, value []byte)
- func (h *RequestHeader) SetHost(host string)
- func (h *RequestHeader) SetHostBytes(host []byte)
- func (h *RequestHeader) SetMethod(method string)
- func (h *RequestHeader) SetMethodBytes(method []byte)
- func (h *RequestHeader) SetMultipartFormBoundary(boundary string)
- func (h *RequestHeader) SetMultipartFormBoundaryBytes(boundary []byte)
- func (h *RequestHeader) SetNoDefaultContentType(noDefaultContentType bool)
- func (h *RequestHeader) SetProtocol(method string)
- func (h *RequestHeader) SetProtocolBytes(method []byte)
- func (h *RequestHeader) SetReferer(referer string)
- func (h *RequestHeader) SetRefererBytes(referer []byte)
- func (h *RequestHeader) SetRequestURI(requestURI string)
- func (h *RequestHeader) SetRequestURIBytes(requestURI []byte)
- func (h *RequestHeader) SetTrailer(trailer string) error
- func (h *RequestHeader) SetTrailerBytes(trailer []byte) error
- func (h *RequestHeader) SetUserAgent(userAgent string)
- func (h *RequestHeader) SetUserAgentBytes(userAgent []byte)
- func (h *RequestHeader) String() string
- func (h *RequestHeader) TrailerHeader() []byte
- func (h *RequestHeader) UserAgent() []byte
- func (h *RequestHeader) VisitAll(f func(key, value []byte))
- func (h *RequestHeader) VisitAllCookie(f func(key, value []byte))
- func (h *RequestHeader) VisitAllInOrder(f func(key, value []byte))
- func (h *RequestHeader) VisitAllTrailer(f func(value []byte))
- func (h *RequestHeader) Write(w *bufio.Writer) error
- func (h *RequestHeader) WriteTo(w io.Writer) (int64, error)
- type Resolver
- type Response
- func (resp *Response) AppendBody(p []byte)
- func (resp *Response) AppendBodyString(s string)
- func (resp *Response) Body() []byte
- func (resp *Response) BodyGunzip() ([]byte, error)
- func (resp *Response) BodyInflate() ([]byte, error)
- func (resp *Response) BodyStream() io.Reader
- func (resp *Response) BodyUncompressed() ([]byte, error)
- func (resp *Response) BodyWriteTo(w io.Writer) error
- func (resp *Response) BodyWriter() io.Writer
- func (resp *Response) CloseBodyStream() error
- func (resp *Response) ConnectionClose() bool
- func (resp *Response) CopyTo(dst *Response)
- func (resp *Response) IsBodyStream() bool
- func (resp *Response) LocalAddr() net.Addr
- func (resp *Response) Read(r *bufio.Reader) error
- func (resp *Response) ReadBody(r *bufio.Reader, maxBodySize int) (err error)
- func (resp *Response) ReadLimitBody(r *bufio.Reader, maxBodySize int) error
- func (resp *Response) ReleaseBody(size int)
- func (resp *Response) RemoteAddr() net.Addr
- func (resp *Response) Reset()
- func (resp *Response) ResetBody()
- func (resp *Response) SendFile(path string) error
- func (resp *Response) SetBody(body []byte)
- func (resp *Response) SetBodyRaw(body []byte)
- func (resp *Response) SetBodyStream(bodyStream io.Reader, bodySize int)
- func (resp *Response) SetBodyStreamWriter(sw StreamWriter)
- func (resp *Response) SetBodyString(body string)
- func (resp *Response) SetConnectionClose()
- func (resp *Response) SetStatusCode(statusCode int)
- func (resp *Response) StatusCode() int
- func (resp *Response) String() string
- func (resp *Response) SwapBody(body []byte) []byte
- func (resp *Response) Write(w *bufio.Writer) error
- func (resp *Response) WriteDeflate(w *bufio.Writer) error
- func (resp *Response) WriteDeflateLevel(w *bufio.Writer, level int) error
- func (resp *Response) WriteGzip(w *bufio.Writer) error
- func (resp *Response) WriteGzipLevel(w *bufio.Writer, level int) error
- func (resp *Response) WriteTo(w io.Writer) (int64, error)
- type ResponseHeader
- func (h *ResponseHeader) Add(key, value string)
- func (h *ResponseHeader) AddBytesK(key []byte, value string)
- func (h *ResponseHeader) AddBytesKV(key, value []byte)
- func (h *ResponseHeader) AddBytesV(key string, value []byte)
- func (h *ResponseHeader) AddTrailer(trailer string) error
- func (h *ResponseHeader) AddTrailerBytes(trailer []byte) error
- func (h *ResponseHeader) AppendBytes(dst []byte) []byte
- func (h *ResponseHeader) ConnectionClose() bool
- func (h *ResponseHeader) ConnectionUpgrade() bool
- func (h *ResponseHeader) ContentEncoding() []byte
- func (h *ResponseHeader) ContentLength() int
- func (h *ResponseHeader) ContentType() []byte
- func (h *ResponseHeader) Cookie(cookie *Cookie) bool
- func (h *ResponseHeader) CopyTo(dst *ResponseHeader)
- func (h *ResponseHeader) Del(key string)
- func (h *ResponseHeader) DelAllCookies()
- func (h *ResponseHeader) DelBytes(key []byte)
- func (h *ResponseHeader) DelClientCookie(key string)
- func (h *ResponseHeader) DelClientCookieBytes(key []byte)
- func (h *ResponseHeader) DelCookie(key string)
- func (h *ResponseHeader) DelCookieBytes(key []byte)
- func (h *ResponseHeader) DisableNormalizing()
- func (h *ResponseHeader) EnableNormalizing()
- func (h *ResponseHeader) Header() []byte
- func (h *ResponseHeader) IsHTTP11() bool
- func (h *ResponseHeader) Len() int
- func (h *ResponseHeader) Peek(key string) []byte
- func (h *ResponseHeader) PeekAll(key string) [][]byte
- func (h *ResponseHeader) PeekBytes(key []byte) []byte
- func (h *ResponseHeader) PeekCookie(key string) []byte
- func (h *ResponseHeader) PeekKeys() [][]byte
- func (h *ResponseHeader) PeekTrailerKeys() [][]byte
- func (h *ResponseHeader) Protocol() []byte
- func (h *ResponseHeader) Read(r *bufio.Reader) error
- func (h *ResponseHeader) ReadTrailer(r *bufio.Reader) error
- func (h *ResponseHeader) Reset()
- func (h *ResponseHeader) ResetConnectionClose()
- func (h *ResponseHeader) Server() []byte
- func (h *ResponseHeader) Set(key, value string)
- func (h *ResponseHeader) SetBytesK(key []byte, value string)
- func (h *ResponseHeader) SetBytesKV(key, value []byte)
- func (h *ResponseHeader) SetBytesV(key string, value []byte)
- func (h *ResponseHeader) SetCanonical(key, value []byte)
- func (h *ResponseHeader) SetConnectionClose()
- func (h *ResponseHeader) SetContentEncoding(contentEncoding string)
- func (h *ResponseHeader) SetContentEncodingBytes(contentEncoding []byte)
- func (h *ResponseHeader) SetContentLength(contentLength int)
- func (h *ResponseHeader) SetContentRange(startPos, endPos, contentLength int)
- func (h *ResponseHeader) SetContentType(contentType string)
- func (h *ResponseHeader) SetContentTypeBytes(contentType []byte)
- func (h *ResponseHeader) SetCookie(cookie *Cookie)
- func (h *ResponseHeader) SetLastModified(t time.Time)
- func (h *ResponseHeader) SetNoDefaultContentType(noDefaultContentType bool)
- func (h *ResponseHeader) SetProtocol(protocol []byte)
- func (h *ResponseHeader) SetServer(server string)
- func (h *ResponseHeader) SetServerBytes(server []byte)
- func (h *ResponseHeader) SetStatusCode(statusCode int)
- func (h *ResponseHeader) SetStatusMessage(statusMessage []byte)
- func (h *ResponseHeader) SetTrailer(trailer string) error
- func (h *ResponseHeader) SetTrailerBytes(trailer []byte) error
- func (h *ResponseHeader) StatusCode() int
- func (h *ResponseHeader) StatusMessage() []byte
- func (h *ResponseHeader) String() string
- func (h *ResponseHeader) TrailerHeader() []byte
- func (h *ResponseHeader) VisitAll(f func(key, value []byte))
- func (h *ResponseHeader) VisitAllCookie(f func(key, value []byte))
- func (h *ResponseHeader) VisitAllTrailer(f func(value []byte))
- func (h *ResponseHeader) Write(w *bufio.Writer) error
- func (h *ResponseHeader) WriteTo(w io.Writer) (int64, error)
- type RetryIfFunc
- type RoundTripper
- type Router
- func (r *Router) Delete(path string, handle Handle) *Router
- func (r *Router) Get(path string, handle Handle) *Router
- func (r *Router) Handle(method, path string, handle Handle) *Router
- func (r *Router) Head(path string, handle Handle) *Router
- func (r *Router) Lookup(method, path string) (Handle, string, Params, bool)
- func (r *Router) Name(name string)
- func (r *Router) Options(path string, handle Handle) *Router
- func (r *Router) Patch(path string, handle Handle) *Router
- func (r *Router) Post(path string, handle Handle) *Router
- func (r *Router) Put(path string, handle Handle) *Router
- func (r *Router) Serve(c *Ctx, middleware func(string, Handle, *Ctx) error) (err error)
- type ServeHandler
- type Server
- func (s *Server) GetCurrentConcurrency() uint32
- func (s *Server) GetOpenConnectionsCount() int32
- func (s *Server) GetRejectedConnectionsCount() uint32
- func (s *Server) GetWorkersCount() (ct int)
- func (s *Server) ListenAndServe(addr string) error
- func (s *Server) ListenAndServeUNIX(addr string, mode os.FileMode) error
- func (s *Server) Serve(ln net.Listener) error
- func (s *Server) ServeConn(c net.Conn) error
- func (s *Server) Shutdown() error
- func (s *Server) ShutdownWithContext(ctx context.Context) (err error)
- type StrMap
- type StreamWriter
- type TCPDialer
- func (d *TCPDialer) Dial(addr string) (net.Conn, error)
- func (d *TCPDialer) DialDualStack(addr string) (net.Conn, error)
- func (d *TCPDialer) DialDualStackTimeout(addr string, timeout time.Duration) (net.Conn, error)
- func (d *TCPDialer) DialTimeout(addr string, timeout time.Duration) (net.Conn, error)
- type URI
- func (u *URI) AppendBytes(dst []byte) []byte
- func (u *URI) CopyTo(dst *URI)
- func (u *URI) FullURI() []byte
- func (u *URI) Hash() []byte
- func (u *URI) Host() []byte
- func (u *URI) LastPathSegment() []byte
- func (u *URI) Parse(host, uri []byte) error
- func (u *URI) Password() []byte
- func (u *URI) Path() []byte
- func (u *URI) PathOriginal() []byte
- func (u *URI) QueryArgs() *Args
- func (u *URI) QueryString() []byte
- func (u *URI) RequestURI() []byte
- func (u *URI) Reset()
- func (u *URI) Scheme() []byte
- func (u *URI) SetHash(hash string)
- func (u *URI) SetHashBytes(hash []byte)
- func (u *URI) SetHost(host string)
- func (u *URI) SetHostBytes(host []byte)
- func (u *URI) SetPassword(password string)
- func (u *URI) SetPasswordBytes(password []byte)
- func (u *URI) SetPath(path string)
- func (u *URI) SetPathBytes(path []byte)
- func (u *URI) SetQueryString(queryString string)
- func (u *URI) SetQueryStringBytes(queryString []byte)
- func (u *URI) SetScheme(scheme string)
- func (u *URI) SetSchemeBytes(scheme []byte)
- func (u *URI) SetUsername(username string)
- func (u *URI) SetUsernameBytes(username []byte)
- func (u *URI) String() string
- func (u *URI) Update(newURI string)
- func (u *URI) UpdateBytes(newURI []byte)
- func (u *URI) Username() []byte
- func (u *URI) WriteTo(w io.Writer) (int64, error)
- type ViewHandler
Examples ¶
Constants ¶
const ( CompressNoCompression = flate.NoCompression CompressBestSpeed = flate.BestSpeed CompressBestCompression = flate.BestCompression CompressDefaultCompression = 6 // flate.DefaultCompression CompressHuffmanOnly = -2 // flate.HuffmanOnly )
Supported compression levels.
const ( StrGzip = "gzip" StrBr = "br" StrDeflate = "deflate" StrBrotli = "brotli" )
const ( MIMETextXML = "text/xml" MIMETextHTML = "text/html" MIMETextPlain = "text/plain" MIMETextJavaScript = "text/javascript" MIMEApplicationXML = "application/xml" MIMEApplicationJSON = "application/json" // Deprecated: use MIMETextJavaScript instead MIMEApplicationJavaScript = "application/javascript" MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEOctetStream = "application/octet-stream" MIMEMultipartForm = "multipart/form-data" MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8" MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8" MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8" MIMETextJavaScriptCharsetUTF8 = "text/javascript; charset=utf-8" MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8" MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8" // Deprecated: use MIMETextJavaScriptCharsetUTF8 instead MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8" )
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.
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.
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 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 StatusInternalServerError = 500 // RFC 7231, 6.6.1 StatusNotImplemented = 501 // RFC 7231, 6.6.2 StatusBadGateway = 502 // RFC 7231, 6.6.3 StatusGatewayTimeout = 504 // RFC 7231, 6.6.5 StatusHTTPVersionNotSupported = 505 // RFC 7231, 6.6.6 StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1 StatusInsufficientStorage = 507 // RFC 4918, 11.5 StatusLoopDetected = 508 // RFC 5842, 7.2 StatusNotExtended = 510 // RFC 2774, 7 StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6 )
HTTP status codes were stolen from net/http.
const DefaultConcurrency = 256 * 1024
DefaultConcurrency is the maximum number of concurrent connections the Server may serve by default (i.e. if Server.Concurrency isn't set).
const DefaultDNSCacheDuration = time.Minute
DefaultDNSCacheDuration is the duration for caching resolved TCP addresses by Dial* functions.
const DefaultDialTimeout = 3 * time.Second
DefaultDialTimeout is timeout used by Dial and DialDualStack for establishing TCP connections.
const DefaultLBClientTimeout = time.Second
DefaultLBClientTimeout is the default request timeout used by LBClient when calling LBClient.Do.
The timeout may be overridden via LBClient.Timeout.
const DefaultMaxConnsPerHost = 512
DefaultMaxConnsPerHost is the maximum number of concurrent connections http client may establish per host by default (i.e. if Client.MaxConnsPerHost isn't set).
const DefaultMaxIdemponentCallAttempts = 5
DefaultMaxIdemponentCallAttempts is the default idempotent calls attempts count.
const DefaultMaxIdleConnDuration = 10 * time.Second
DefaultMaxIdleConnDuration is the default duration before idle keep-alive connection is closed.
const DefaultMaxPendingRequests = 1024
DefaultMaxPendingRequests is the default value for PipelineClient.MaxPendingRequests.
const DefaultMaxRequestBodySize = 4 * 1024 * 1024
DefaultMaxRequestBodySize is the maximum request body size the server reads by default.
See Server.MaxRequestBodySize for details.
const FSCompressedFileSuffix = ".fasthttp.gz"
FSCompressedFileSuffix is the suffix FS adds to the original file names when trying to store compressed file under the new file name. See FS.Compress for details.
const FSHandlerCacheDuration = 10 * time.Second
FSHandlerCacheDuration is the default expiration duration for inactive file handlers opened by FS.
const LayoutEmbed = "embed"
const MatchedRoutePathKey = "_matched_route_path_"
MatchedRoutePathKey is the Param name under which the path of the matched route is stored, if Router.SaveMatchedRoutePath is set.
const ReqStartTimeKey = "_req_start_time_"
ReqStartTimeKey is request start time key
const StatusTooEarly = 425
const (
ViewHandlerKey = "_view_handler_"
)
Variables ¶
var ( // ErrMissingLocation is returned by clients when the Location header is missing on // an HTTP response with a redirect status code. ErrMissingLocation = errors.New("missing Location header for http redirect") // ErrTooManyRedirects is returned by clients when the number of redirects followed // exceed the max count. ErrTooManyRedirects = errors.New("too many redirects detected when doing the request") // HostClients are only able to follow redirects to the same protocol. ErrHostClientRedirectToDifferentScheme = errors.New("HostClient can't follow redirects to a different protocol," + " please use Client instead") )
var ( // ErrNoFreeConns is returned when no free connections available // to the given host. // // Increase the allowed number of connections per host if you // see this error. ErrNoFreeConns = errors.New("no free connections available to host") // ErrConnectionClosed may be returned from client methods if the server // closes connection before returning the first response byte. // // If you see this error, then either fix the server by returning // 'Connection: close' response header before closing the connection // or add 'Connection: close' request header before sending requests // to broken server. ErrConnectionClosed = errors.New("the server closed connection before returning the first response byte. " + "Make sure the server returns 'Connection: close' response header before closing the connection") // ErrConnPoolStrategyNotImpl is returned when HostClient.ConnPoolStrategy is not implement yet. // If you see this error, then you need to check your HostClient configuration. ErrConnPoolStrategyNotImpl = errors.New("connection pool strategy is not implement") )
var ( // CookieExpireDelete may be set on Cookie.Expire for expiring the given cookie. CookieExpireDelete = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) // CookieExpireUnlimited indicates that the cookie doesn't expire. CookieExpireUnlimited = zeroTime )
var ( ErrBadRequest = NewError(StatusBadRequest) // 400 ErrPaymentRequired = NewError(StatusPaymentRequired) // 402 ErrForbidden = NewError(StatusForbidden) // 403 ErrNotFound = NewError(StatusNotFound) // 404 ErrMethodNotAllowed = NewError(StatusMethodNotAllowed) // 405 ErrNotAcceptable = NewError(StatusNotAcceptable) // 406 ErrProxyAuthRequired = NewError(StatusProxyAuthRequired) // 407 ErrRequestTimeout = NewError(StatusRequestTimeout) // 408 ErrConflict = NewError(StatusConflict) // 409 ErrGone = NewError(StatusGone) // 410 ErrLengthRequired = NewError(StatusLengthRequired) // 411 ErrPreconditionFailed = NewError(StatusPreconditionFailed) // 412 ErrRequestEntityTooLarge = NewError(StatusRequestEntityTooLarge) // 413 ErrRequestURITooLong = NewError(StatusRequestURITooLong) // 414 ErrUnsupportedMediaType = NewError(StatusUnsupportedMediaType) // 415 ErrRequestedRangeNotSatisfiable = NewError(StatusRequestedRangeNotSatisfiable) // 416 ErrExpectationFailed = NewError(StatusExpectationFailed) // 417 ErrTeapot = NewError(StatusTeapot) // 418 ErrMisdirectedRequest = NewError(StatusMisdirectedRequest) // 421 ErrUnprocessableEntity = NewError(StatusUnprocessableEntity) // 422 ErrLocked = NewError(StatusLocked) // 423 ErrFailedDependency = NewError(StatusFailedDependency) // 424 ErrTooEarly = NewError(StatusTooEarly) // 425 ErrUpgradeRequired = NewError(StatusUpgradeRequired) // 426 ErrPreconditionRequired = NewError(StatusPreconditionRequired) // 428 ErrTooManyRequests = NewError(StatusTooManyRequests) // 429 ErrRequestHeaderFieldsTooLarge = NewError(StatusRequestHeaderFieldsTooLarge) // 431 ErrInternalServerError = NewError(StatusInternalServerError) // 500 ErrNotImplemented = NewError(StatusNotImplemented) // 501 ErrBadGateway = NewError(StatusBadGateway) // 502 ErrGatewayTimeout = NewError(StatusGatewayTimeout) // 504 ErrHTTPVersionNotSupported = NewError(StatusHTTPVersionNotSupported) // 505 ErrVariantAlsoNegotiates = NewError(StatusVariantAlsoNegotiates) // 506 ErrInsufficientStorage = NewError(StatusInsufficientStorage) // 507 ErrLoopDetected = NewError(StatusLoopDetected) // 508 ErrNotExtended = NewError(StatusNotExtended) // 510 ErrNetworkAuthenticationRequired = NewError(StatusNetworkAuthenticationRequired) // 511 )
Errors
var ( ErrRangeMalformed = errors.New("range: malformed range header string") ErrRangeUnsatisfiable = errors.New("range: unsatisfiable range") )
var ( // ErrPerIPConnLimit may be returned from ServeConn if the number of connections // per ip exceeds Server.MaxConnsPerIP. ErrPerIPConnLimit = errors.New("too many connections per ip") // ErrConcurrencyLimit may be returned from ServeConn if the number // of concurrently served connections exceeds Server.Concurrency. ErrConcurrencyLimit = errors.New("cannot serve the connection because Server.Concurrency concurrent connections are served") )
var DefaultBinder = &binder{}
var ErrAlreadyServing = errors.New("Server is already serving connections")
ErrAlreadyServing is deprecated. Deprecated: ErrAlreadyServing is never returned from Serve. See issue #633.
var ErrBadTrailer = errors.New("contain forbidden trailer")
var ErrBodyTooLarge = errors.New("body size exceeds the given limit")
ErrBodyTooLarge is returned if either request or response body exceeds the given limit.
var ErrContentEncodingUnsupported = errors.New("unsupported Content-Encoding")
var ErrDialTimeout = errors.New("dialing to the given TCP address timed out")
ErrDialTimeout is returned when TCP dialing is timed out.
var ErrEmbedCalled = errors.New("embed called directly")
var ErrGetOnly = errors.New("non-GET request received")
ErrGetOnly is returned when server expects only GET requests, but some other type of request came (Server.GetOnly option is true).
var ErrMissingFile = errors.New("there is no uploaded file associated with the given key")
ErrMissingFile may be returned from FormFile when the is no uploaded file associated with the given multipart form key.
var ErrNoArgValue = errors.New("no Args value for the given key")
ErrNoArgValue is returned when Args value with the given key is missing.
var ErrNoMultipartForm = errors.New("request Content-Type has bad boundary or is not multipart/form-data")
ErrNoMultipartForm means that the request's Content-Type isn't 'multipart/form-data'.
var ErrNoViewRenderer = errors.New("view renderer not configured")
var ErrPipelineOverflow = errors.New("pipelined requests' queue has been overflowed. Increase MaxConns and/or MaxPendingRequests")
ErrPipelineOverflow may be returned from PipelineClient.Do* if the requests' queue is overflowed.
var ErrTLSHandshakeTimeout = errors.New("tls handshake timed out")
ErrTLSHandshakeTimeout indicates there is a timeout from tls handshake.
var ErrTimeout = &timeoutError{}
ErrTimeout is returned from timed out calls.
var ErrorInvalidURI = errors.New("invalid uri")
var FSCompressedFileSuffixes = map[string]string{
"gzip": ".fasthttp.gz",
"br": ".fasthttp.br",
"zstd": ".fasthttp.zst",
}
FSCompressedFileSuffixes is the suffixes FS adds to the original file names depending on encoding when trying to store compressed file under the new file name. See FS.Compress for details.
var ( // NetHttpFormValueFunc gives consistent behavior with net/http. // POST and PUT body parameters take precedence over URL query string values. // //nolint:stylecheck // backwards compatibility NetHttpFormValueFunc = func(ctx *RequestCtx, key string) []byte { v := ctx.PostArgs().Peek(key) if len(v) > 0 { return v } mf, err := ctx.MultipartForm() if err == nil && mf.Value != nil { vv := mf.Value[key] if len(vv) > 0 { return []byte(vv[0]) } } v = ctx.QueryArgs().Peek(key) if len(v) > 0 { return v } return nil } )
var ParamsKey = paramsKey{}
ParamsKey is the request context key under which URL params are stored.
Functions ¶
func AcquireTimer ¶
AcquireTimer returns a time.Timer from the pool and updates it to send the current time on its channel after at least timeout.
The returned Timer may be returned to the pool with ReleaseTimer when no longer needed. This allows reducing GC load.
func AddMissingPort ¶
AddMissingPort adds a port to a host if it is missing. A literal IPv6 address in hostport must be enclosed in square brackets, as in "[::1]:80", "[::1%lo0]:80".
func AppendDeflateBytes ¶
AppendDeflateBytes appends deflated src to dst and returns the resulting dst.
func AppendDeflateBytesLevel ¶
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 ¶
AppendGunzipBytes appends gunzipped src to dst and returns the resulting dst.
func AppendGzipBytes ¶
AppendGzipBytes appends gzipped src to dst and returns the resulting dst.
func AppendGzipBytesLevel ¶
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 ¶
AppendHTMLEscape appends html-escaped s to dst and returns the extended dst.
func AppendHTMLEscapeBytes ¶
AppendHTMLEscapeBytes appends html-escaped s to dst and returns the extended dst.
func AppendHTTPDate ¶
AppendHTTPDate appends HTTP-compliant (RFC1123) representation of date to dst and returns the extended dst.
func AppendIPv4 ¶
AppendIPv4 appends string representation of the given ip v4 to dst and returns the extended dst.
func AppendInflateBytes ¶
AppendInflateBytes appends inflated src to dst and returns the resulting dst.
func AppendNormalizedHeaderKey ¶
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 ¶
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 ¶
AppendQuotedArg appends url-encoded src to dst and returns appended dst.
func AppendUint ¶
AppendUint appends n to dst and returns the extended dst.
func AppendUnquotedArg ¶
AppendUnquotedArg appends url-decoded src to dst and returns appended dst.
dst may point to src. In this case src will be overwritten.
func CleanPath ¶
CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.
The following rules are applied iteratively until no further processing can be done:
- Replace multiple slashes with a single slash.
- Eliminate each . path name element (the current directory).
- Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
- Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.
If the result of this process is an empty string, "/" is returned
func CoarseTimeNow
deprecated
func Dial ¶
Dial dials the given TCP addr using tcp4.
This function has the following additional features comparing to net.Dial:
- It reduces load on DNS resolver by caching resolved TCP addressed for DNSCacheDuration.
- It dials all the resolved TCP addresses in round-robin manner until connection is established. This may be useful if certain addresses are temporarily unreachable.
- It returns ErrDialTimeout if connection cannot be established during DefaultDialTimeout seconds. Use DialTimeout for customizing dial timeout.
This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial.
For instance, per-host counters and/or limits may be implemented by such wrappers.
The addr passed to the function must contain port. Example addr values:
- foobar.baz:443
- foo.bar:80
- aaa.com:8080
func DialDualStack ¶
DialDualStack dials the given TCP addr using both tcp4 and tcp6.
This function has the following additional features comparing to net.Dial:
- It reduces load on DNS resolver by caching resolved TCP addressed for DNSCacheDuration.
- It dials all the resolved TCP addresses in round-robin manner until connection is established. This may be useful if certain addresses are temporarily unreachable.
- It returns ErrDialTimeout if connection cannot be established during DefaultDialTimeout seconds. Use DialDualStackTimeout for custom dial timeout.
This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial.
For instance, per-host counters and/or limits may be implemented by such wrappers.
The addr passed to the function must contain port. Example addr values:
- foobar.baz:443
- foo.bar:80
- aaa.com:8080
func DialDualStackTimeout ¶
DialDualStackTimeout dials the given TCP addr using both tcp4 and tcp6 using the given timeout.
This function has the following additional features comparing to net.Dial:
- It reduces load on DNS resolver by caching resolved TCP addressed for DNSCacheDuration.
- It dials all the resolved TCP addresses in round-robin manner until connection is established. This may be useful if certain addresses are temporarily unreachable.
This dialer is intended for custom code wrapping before passing to Client.DialTimeout or HostClient.DialTimeout.
For instance, per-host counters and/or limits may be implemented by such wrappers.
The addr passed to the function must contain port. Example addr values:
- foobar.baz:443
- foo.bar:80
- aaa.com:8080
func DialTimeout ¶
DialTimeout dials the given TCP addr using tcp4 using the given timeout.
This function has the following additional features comparing to net.Dial:
- It reduces load on DNS resolver by caching resolved TCP addressed for DNSCacheDuration.
- It dials all the resolved TCP addresses in round-robin manner until connection is established. This may be useful if certain addresses are temporarily unreachable.
This dialer is intended for custom code wrapping before passing to Client.DialTimeout or HostClient.DialTimeout.
For instance, per-host counters and/or limits may be implemented by such wrappers.
The addr passed to the function must contain port. Example addr values:
- foobar.baz:443
- foo.bar:80
- aaa.com:8080
func Do ¶
Do performs the given http request and fills the given http response.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
Client determines the server to be requested in the following order:
- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.
The function doesn't follow redirects. Use Get* for following redirects.
Response is ignored if resp is nil.
ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func DoDeadline ¶
DoDeadline performs the given request and waits for response until the given deadline.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
Client determines the server to be requested in the following order:
- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.
The function doesn't follow redirects. Use Get* for following redirects.
Response is ignored if resp is nil.
ErrTimeout is returned if the response wasn't returned until the given deadline.
ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func DoRedirects ¶
DoRedirects performs the given http request and fills the given http response, following up to maxRedirectsCount redirects. When the redirect count exceeds maxRedirectsCount, ErrTooManyRedirects is returned.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
Client determines the server to be requested in the following order:
- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.
Response is ignored if resp is nil.
ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func DoTimeout ¶
DoTimeout performs the given request and waits for response during the given timeout duration.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
Client determines the server to be requested in the following order:
- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.
The function doesn't follow redirects. Use Get* for following redirects.
Response is ignored if resp is nil.
ErrTimeout is returned if the response wasn't returned during the given timeout.
ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func FileLastModified ¶
FileLastModified returns last modified time for the file.
func GenerateTestCertificate ¶
GenerateTestCertificate generates a test certificate and private key based on the given host.
func Get ¶
Get returns the status code and body of url.
The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated.
The function follows redirects. Use Do* for manually handling redirects.
func GetDeadline ¶
func GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error)
GetDeadline returns the status code and body of url.
The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated.
The function follows redirects. Use Do* for manually handling redirects.
ErrTimeout error is returned if url contents couldn't be fetched until the given deadline.
func GetTimeout ¶
func GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error)
GetTimeout returns the status code and body of url.
The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated.
The function follows redirects. Use Do* for manually handling redirects.
ErrTimeout error is returned if url contents couldn't be fetched during the given timeout.
func ListenAndServe ¶
func ListenAndServe(addr string, handler RequestHandler) error
ListenAndServe serves HTTP requests from the given TCP addr using the given handler.
Example ¶
package main import ( "fmt" "log" "github.com/adhocore/fasthttp" ) func main() { // The server will listen for incoming requests on this address. listenAddr := "127.0.0.1:80" // This function will be called by the server for each incoming request. // // RequestCtx provides a lot of functionality related to http request // processing. See RequestCtx docs for details. requestHandler := func(ctx *fasthttp.RequestCtx) { fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path()) } // Start the server with default settings. // Create Server instance for adjusting server settings. // // ListenAndServe returns only on error, so usually it blocks forever. if err := fasthttp.ListenAndServe(listenAddr, requestHandler); err != nil { log.Fatalf("error in ListenAndServe: %v", err) } }
Output:
func ListenAndServeUNIX ¶
func ListenAndServeUNIX(addr string, mode os.FileMode, handler RequestHandler) error
ListenAndServeUNIX serves HTTP requests from the given UNIX addr using the given handler.
The function deletes existing file at addr before starting serving.
The server sets the given file mode for the UNIX addr.
func NewStreamReader ¶
func NewStreamReader(sw StreamWriter) io.ReadCloser
NewStreamReader returns a reader, which replays all the data generated by sw.
The returned reader may be passed to Response.SetBodyStream.
Close must be called on the returned reader after all the required data has been read. Otherwise goroutine leak may occur.
See also Response.SetBodyStreamWriter.
func ParseByteRange ¶
ParseByteRange parses 'Range: bytes=...' header value.
It follows https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 .
func ParseHTTPDate ¶
ParseHTTPDate parses HTTP-compliant (RFC1123) date.
func ParseUfloat ¶
ParseUfloat parses unsigned float from buf.
func Post ¶
Post sends POST request to the given url with the given POST arguments.
The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated.
The function follows redirects. Use Do* for manually handling redirects.
Empty POST body is sent if postArgs is nil.
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.
It is forbidden accessing req and/or its' members after returning it to request pool.
func ReleaseResponse ¶
func ReleaseResponse(resp *Response)
ReleaseResponse return resp acquired via AcquireResponse to response pool.
It is forbidden accessing resp and/or its' members after returning it to response pool.
func ReleaseTimer ¶
ReleaseTimer returns the time.Timer acquired via AcquireTimer to the pool and prevents the Timer from firing.
Do not access the released time.Timer or read from its channel otherwise data races may occur.
func ReleaseURI ¶
func ReleaseURI(u *URI)
ReleaseURI releases the URI acquired via AcquireURI.
The released URI mustn't be used after releasing it, otherwise data races may occur.
func SaveMultipartFile ¶
func SaveMultipartFile(fh *multipart.FileHeader, path string) (err error)
SaveMultipartFile saves multipart file fh under the given filename path.
func Serve ¶
func Serve(ln net.Listener, handler RequestHandler) error
Serve serves incoming connections from the given listener using the given handler.
Serve blocks until the given listener returns permanent error.
Example ¶
package main import ( "fmt" "log" "net" "github.com/adhocore/fasthttp" ) func main() { // Create network listener for accepting incoming requests. // // Note that you are not limited by TCP listener - arbitrary // net.Listener may be used by the server. // For example, unix socket listener or TLS listener. ln, err := net.Listen("tcp4", "127.0.0.1:8080") if err != nil { log.Fatalf("error in net.Listen: %v", err) } // This function will be called by the server for each incoming request. // // RequestCtx provides a lot of functionality related to http request // processing. See RequestCtx docs for details. requestHandler := func(ctx *fasthttp.RequestCtx) { fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path()) } // Start the server with default settings. // Create Server instance for adjusting server settings. // // Serve returns on ln.Close() or error, so usually it blocks forever. if err := fasthttp.Serve(ln, requestHandler); err != nil { log.Fatalf("error in Serve: %v", err) } }
Output:
func ServeConn ¶
func ServeConn(c net.Conn, handler RequestHandler) error
ServeConn serves HTTP requests from the given connection using the given handler.
ServeConn returns nil if all requests from the c are successfully served. It returns non-nil error otherwise.
Connection c must immediately propagate all the data passed to Write() to the client. Otherwise requests' processing may hang.
ServeConn closes c before returning.
func ServeFS ¶
func ServeFS(ctx *RequestCtx, filesystem fs.FS, path string)
ServeFS returns HTTP response containing compressed file contents from the given fs.FS's path.
HTTP response may contain uncompressed file contents in the following cases:
- Missing 'Accept-Encoding: gzip' request header.
- No write access to directory containing the file.
Directory contents is returned if path points to directory.
See also ServeFile.
func ServeFile ¶
func ServeFile(ctx *RequestCtx, path string)
ServeFile returns HTTP response containing compressed file contents from the given path.
HTTP response may contain uncompressed file contents in the following cases:
- Missing 'Accept-Encoding: gzip' request header.
- No write access to directory containing the file.
Directory contents is returned if path points to directory.
Use ServeFileUncompressed is you don't need serving compressed file contents.
See also RequestCtx.SendFile.
WARNING: do not pass any user supplied paths to this function! WARNING: if path is based on user input users will be able to request any file on your filesystem! Use fasthttp.FS with a sane Root instead.
func ServeFileBytes ¶
func ServeFileBytes(ctx *RequestCtx, path []byte)
ServeFileBytes returns HTTP response containing compressed file contents from the given path.
HTTP response may contain uncompressed file contents in the following cases:
- Missing 'Accept-Encoding: gzip' request header.
- No write access to directory containing the file.
Directory contents is returned if path points to directory.
Use ServeFileBytesUncompressed is you don't need serving compressed file contents.
See also RequestCtx.SendFileBytes.
WARNING: do not pass any user supplied paths to this function! WARNING: if path is based on user input users will be able to request any file on your filesystem! Use fasthttp.FS with a sane Root instead.
func ServeFileBytesUncompressed ¶
func ServeFileBytesUncompressed(ctx *RequestCtx, path []byte)
ServeFileBytesUncompressed returns HTTP response containing file contents from the given path.
Directory contents is returned if path points to directory.
ServeFileBytes may be used for saving network traffic when serving files with good compression ratio.
See also RequestCtx.SendFileBytes.
WARNING: do not pass any user supplied paths to this function! WARNING: if path is based on user input users will be able to request any file on your filesystem! Use fasthttp.FS with a sane Root instead.
func ServeFileUncompressed ¶
func ServeFileUncompressed(ctx *RequestCtx, path string)
ServeFileUncompressed returns HTTP response containing file contents from the given path.
Directory contents is returned if path points to directory.
ServeFile may be used for saving network traffic when serving files with good compression ratio.
See also RequestCtx.SendFile.
WARNING: do not pass any user supplied paths to this function! WARNING: if path is based on user input users will be able to request any file on your filesystem! Use fasthttp.FS with a sane Root instead.
func SetBodySizePoolLimit ¶
func SetBodySizePoolLimit(reqBodyLimit, respBodyLimit int)
SetBodySizePoolLimit set the max body size for bodies to be returned to the pool. If the body size is larger it will be released instead of put back into the pool for reuse.
func StatusCodeIsRedirect ¶
StatusCodeIsRedirect returns true if the status code indicates a redirect.
func StatusMessage ¶
StatusMessage returns HTTP status message for the given status code.
func VisitHeaderParams ¶
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 ¶
WriteDeflate writes deflated p to w and returns the number of compressed bytes written to w.
func WriteDeflateLevel ¶
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 ¶
WriteGunzip writes ungzipped p to w and returns the number of uncompressed bytes written to w.
func WriteGzip ¶
WriteGzip writes gzipped p to w and returns the number of compressed bytes written to w.
func WriteGzipLevel ¶
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 ¶
WriteInflate writes inflated p to w and returns the number of uncompressed bytes written to w.
Types ¶
type App ¶
type App struct { *Router *Server View *Render Start time.Time // contains filtered or unexported fields }
App is application
func (*App) ServerHandler ¶
ServerHandler (re)sets handler for server and returns it
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) AddBytesK ¶
AddBytesK adds 'key=value' argument.
Multiple values for the same key may be added.
func (*Args) AddBytesKNoValue ¶
AddBytesKNoValue adds only 'key' as argument without the '='.
Multiple values for the same key may be added.
func (*Args) AddBytesKV ¶
AddBytesKV adds 'key=value' argument.
Multiple values for the same key may be added.
func (*Args) AddBytesV ¶
AddBytesV adds 'key=value' argument.
Multiple values for the same key may be added.
func (*Args) AddNoValue ¶
AddNoValue adds only 'key' as argument without the '='.
Multiple values for the same key may be added.
func (*Args) AppendBytes ¶
AppendBytes appends query string to dst and returns the extended dst.
func (*Args) GetBool ¶
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) GetUfloatOrZero ¶
GetUfloatOrZero returns ufloat value for the given key.
Zero (0) is returned on error.
func (*Args) GetUintOrZero ¶
GetUintOrZero returns uint value for the given key.
Zero (0) is returned on error.
func (*Args) ParseBytes ¶
ParseBytes parses the given b containing query args.
func (*Args) Peek ¶
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 ¶
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) PeekMultiBytes ¶
PeekMultiBytes returns all the arg values for the given key.
func (*Args) QueryString ¶
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) SetBytesKNoValue ¶
SetBytesKNoValue sets 'key' argument.
func (*Args) SetBytesKV ¶
SetBytesKV sets 'key=value' argument.
func (*Args) SetNoValue ¶
SetNoValue sets only 'key' as argument without the '='.
Only key in argument, like key1&key2.
func (*Args) SetUintBytes ¶
SetUintBytes sets uint value for the given key.
func (*Args) Sort ¶
Sort sorts Args by key and then value using 'f' as comparison function.
For example args.Sort(bytes.Compare).
type BalancingClient ¶
type BalancingClient interface { DoDeadline(req *Request, resp *Response, deadline time.Time) error PendingRequests() int }
BalancingClient is the interface for clients, which may be passed to LBClient.Clients.
type Client ¶
type Client struct { // Callback for establishing new connections to hosts. // // Default DialTimeout is used if not set. DialTimeout DialFuncWithTimeout // Callback for establishing new connections to hosts. // // Note that if Dial is set instead of DialTimeout, Dial will ignore Request timeout. // If you want the tcp dial process to account for request timeouts, use DialTimeout instead. // // If not set, DialTimeout is used. Dial DialFunc // TLS config for https connections. // // Default TLS config is used if not set. TLSConfig *tls.Config // RetryIf controls whether a retry should be attempted after an error. // // By default will use isIdempotent function. RetryIf RetryIfFunc // ConfigureClient configures the fasthttp.HostClient. ConfigureClient func(hc *HostClient) error // Client name. Used in User-Agent request header. // // Default client name is used if not set. Name string // Maximum number of connections per each host which may be established. // // DefaultMaxConnsPerHost is used if not set. MaxConnsPerHost int // Idle keep-alive connections are closed after this duration. // // By default idle connections are closed // after DefaultMaxIdleConnDuration. MaxIdleConnDuration time.Duration // Keep-alive connections are closed after this duration. // // By default connection duration is unlimited. MaxConnDuration time.Duration // Maximum number of attempts for idempotent calls. // // DefaultMaxIdemponentCallAttempts is used if not set. MaxIdemponentCallAttempts int // Per-connection buffer size for responses' reading. // This also limits the maximum header size. // // Default buffer size is used if 0. ReadBufferSize int // Per-connection buffer size for requests' writing. // // Default buffer size is used if 0. WriteBufferSize int // Maximum duration for full response reading (including body). // // By default response read timeout is unlimited. ReadTimeout time.Duration // Maximum duration for full request writing (including body). // // By default request write timeout is unlimited. WriteTimeout time.Duration // Maximum response body size. // // The client returns ErrBodyTooLarge if this limit is greater than 0 // and response body is greater than the limit. // // By default response body size is unlimited. MaxResponseBodySize int // Maximum duration for waiting for a free connection. // // By default will not waiting, return ErrNoFreeConns immediately. MaxConnWaitTimeout time.Duration // Connection pool strategy. Can be either LIFO or FIFO (default). ConnPoolStrategy ConnPoolStrategyType // NoDefaultUserAgentHeader when set to true, causes the default // User-Agent header to be excluded from the Request. NoDefaultUserAgentHeader bool // Attempt to connect to both ipv4 and ipv6 addresses if set to true. // // This option is used only if default TCP dialer is used, // i.e. if Dial is blank. // // By default client connects only to ipv4 addresses, // since unfortunately ipv6 remains broken in many networks worldwide :) DialDualStack bool // Header names are passed as-is without normalization // if this option is set. // // Disabled header names' normalization may be useful only for proxying // responses to other clients expecting case-sensitive // header names. See https://github.com/valyala/fasthttp/issues/57 // for details. // // By default request and response header names are normalized, i.e. // The first letter and the first letters following dashes // are uppercased, while all the other letters are lowercased. // Examples: // // * HOST -> Host // * content-type -> Content-Type // * cONTENT-lenGTH -> Content-Length DisableHeaderNamesNormalizing bool // 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 // StreamResponseBody enables response body streaming. StreamResponseBody bool // contains filtered or unexported fields }
Client implements http client.
Copying Client by value is prohibited. Create new instance instead.
It is safe calling Client methods from concurrently running goroutines.
The fields of a Client should not be changed while it is in use.
func (*Client) CloseIdleConnections ¶
func (c *Client) CloseIdleConnections()
CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.
func (*Client) Do ¶
Do performs the given http request and fills the given http response.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
Client determines the server to be requested in the following order:
- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.
Response is ignored if resp is nil.
The function doesn't follow redirects. Use Get* for following redirects.
ErrNoFreeConns is returned if all Client.MaxConnsPerHost connections to the requested host are busy.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func (*Client) DoDeadline ¶
DoDeadline performs the given request and waits for response until the given deadline.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
Client determines the server to be requested in the following order:
- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.
The function doesn't follow redirects. Use Get* for following redirects.
Response is ignored if resp is nil.
ErrTimeout is returned if the response wasn't returned until the given deadline. Immediately returns ErrTimeout if the deadline has already been reached.
ErrNoFreeConns is returned if all Client.MaxConnsPerHost connections to the requested host are busy.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func (*Client) DoRedirects ¶
DoRedirects performs the given http request and fills the given http response, following up to maxRedirectsCount redirects. When the redirect count exceeds maxRedirectsCount, ErrTooManyRedirects is returned.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
Client determines the server to be requested in the following order:
- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.
Response is ignored if resp is nil.
ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func (*Client) DoTimeout ¶
DoTimeout performs the given request and waits for response during the given timeout duration.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
Client determines the server to be requested in the following order:
- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.
The function doesn't follow redirects. Use Get* for following redirects.
Response is ignored if resp is nil.
ErrTimeout is returned if the response wasn't returned during the given timeout. Immediately returns ErrTimeout if timeout value is negative.
ErrNoFreeConns is returned if all Client.MaxConnsPerHost connections to the requested host are busy.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func (*Client) Get ¶
Get returns the status code and body of url.
The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated.
The function follows redirects. Use Do* for manually handling redirects.
func (*Client) GetDeadline ¶
func (c *Client) GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error)
GetDeadline returns the status code and body of url.
The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated.
The function follows redirects. Use Do* for manually handling redirects.
ErrTimeout error is returned if url contents couldn't be fetched until the given deadline.
func (*Client) GetTimeout ¶
func (c *Client) GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error)
GetTimeout returns the status code and body of url.
The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated.
The function follows redirects. Use Do* for manually handling redirects.
ErrTimeout error is returned if url contents couldn't be fetched during the given timeout.
func (*Client) Post ¶
func (c *Client) Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error)
Post sends POST request to the given url with the given POST arguments.
The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated.
The function follows redirects. Use Do* for manually handling redirects.
Empty POST body is sent if postArgs is nil.
type ConnPoolStrategyType ¶
type ConnPoolStrategyType int
ConnPoolStrategyType define strategy of connection pool enqueue/dequeue.
const ( FIFO ConnPoolStrategyType = iota LIFO )
type ConnState ¶
type ConnState int
A ConnState represents the state of a client connection to a server. It's used by the optional Server.ConnState hook.
const ( // StateNew represents a new connection that is expected to // send a request immediately. Connections begin at this // state and then transition to either StateActive or // StateClosed. StateNew ConnState = iota // StateActive represents a connection that has read 1 or more // bytes of a request. The Server.ConnState hook for // StateActive fires before the request has entered a handler // and doesn't fire again until the request has been // handled. After the request is handled, the state // transitions to StateClosed, StateHijacked, or StateIdle. // For HTTP/2, StateActive fires on the transition from zero // to one active request, and only transitions away once all // active requests are complete. That means that ConnState // cannot be used to do per-request work; ConnState only notes // the overall state of the connection. StateActive // StateIdle represents a connection that has finished // handling a request and is in the keep-alive state, waiting // for a new request. Connections transition from StateIdle // to either StateActive or StateClosed. StateIdle // StateHijacked represents a hijacked connection. // This is a terminal state. It does not transition to StateClosed. StateHijacked // StateClosed represents a closed connection. // This is a terminal state. Hijacked connections do not // transition to StateClosed. StateClosed )
type Cookie ¶
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 ¶
AppendBytes appends cookie representation to dst and returns the extended dst.
func (*Cookie) Cookie ¶
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) Domain ¶
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 ¶
Expire returns cookie expiration time.
CookieExpireUnlimited is returned if cookie doesn't expire.
func (*Cookie) Key ¶
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 ¶
MaxAge returns the seconds until the cookie is meant to expire or 0 if no max age.
func (*Cookie) ParseBytes ¶
ParseBytes parses Set-Cookie header.
func (*Cookie) Partitioned ¶
Partitioned returns true if the cookie is partitioned.
func (*Cookie) SameSite ¶
func (c *Cookie) SameSite() CookieSameSite
SameSite returns the SameSite mode.
func (*Cookie) SetDomainBytes ¶
SetDomainBytes sets cookie domain.
func (*Cookie) SetExpire ¶
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 ¶
SetHTTPOnly sets cookie's httpOnly flag to the given value.
func (*Cookie) SetMaxAge ¶
SetMaxAge sets cookie expiration time based on seconds. This takes precedence over any absolute expiry set on the cookie.
Set max age to 0 to unset.
func (*Cookie) SetPartitioned ¶
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) SetPathBytes ¶
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) SetValueBytes ¶
SetValueBytes sets cookie value.
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 Cookiex ¶
type Cookiex struct { Expires time.Time `json:"expires"` Name string `json:"name"` Value string `json:"value"` Path string `json:"path"` Domain string `json:"domain"` SameSite CookieSameSite `json:"same_site"` MaxAge int `json:"max_age"` Secure bool `json:"secure"` HTTPOnly bool `json:"http_only"` SessionOnly bool `json:"session_only"` }
Cookiex is a cookie with exported string fields Use like c.Cookie(&Cookiex{Name: "...", Value: "..."})
type Ctx ¶
type Ctx = RequestCtx
func (*Ctx) AllParams ¶
AllParams Params is used to get all route parameters. Using Params method to get params.
func (*Ctx) Append ¶
Append the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value.
func (*Ctx) Attachment ¶
Attachment sets the HTTP response Content-Disposition header field to attachment.
func (*Ctx) Bind ¶
Bind Add vars to default view var map binding to template engine. Variables are read by the Render method and may be overwritten.
func (*Ctx) Body ¶
Body contains the raw body submitted in a POST request. This method will decompress the body if the 'Content-Encoding' header is provided. It returns the original (or decompressed) body data which is valid only within the handler. Don't store direct references to the returned data. If you need to keep the body's data later, make a copy or use the Immutable option.
func (*Ctx) BodyParser ¶
BodyParser binds the request body to a struct. It supports decoding the following content types based on the Content-Type header: application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data All JSON extenstion mime types are supported (eg. application/problem+json) If none of the content types above are matched, it will return a ErrUnprocessableEntity error
func (*Ctx) BodyRaw ¶
BodyRaw contains the raw body submitted in a POST request. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.
func (*Ctx) ClearCookie ¶
ClearCookie expires a specific cookie by key on the client side. If no key is provided it expires all cookies that came with the request.
func (*Ctx) ClientHelloInfo ¶
func (c *Ctx) ClientHelloInfo() *tls.ClientHelloInfo
ClientHelloInfo return CHI from context
func (*Ctx) Cookie ¶
Cookie sets a cookie by passing a cookie struct. Use like c.Cookie(&Cookiex{Name: "...", Value: "..."})
func (*Ctx) CookieParser ¶
CookieParser is used to bind cookies to a struct
func (*Ctx) Cookies ¶
Cookies are used for getting a cookie value by key. Defaults to the empty string "" if the cookie doesn't exist. If a default value is given, it will return that value if the cookie doesn't exist. The returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting to use the value outside the Handler.
func (*Ctx) Download ¶
Download transfers the file from path as an attachment. Typically, browsers will prompt the user for download. By default, the Content-Disposition header filename= parameter is the filepath (this typically appears in the browser dialog). Override this default with the filename parameter.
func (*Ctx) FormParams ¶
FormParams give request form params from GET+POST+FILES
func (*Ctx) FormValues ¶
FormValues gives form value from request in order GET > POST > FILES
func (*Ctx) Format ¶
Format performs content-negotiation on the Accept HTTP header. It uses Accepts to select a proper format. If the header is not specified or there is no proper format, text/plain is used.
func (*Ctx) Get ¶
Get returns the HTTP request header specified by field. Field names are case-insensitive Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.
func (*Ctx) GetReqHeaders ¶
GetReqHeaders returns the HTTP request headers. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.
func (*Ctx) GetRespHeader ¶
GetRespHeader returns the HTTP response header specified by field. Field names are case-insensitive Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.
func (*Ctx) GetRespHeaders ¶
GetRespHeaders returns the HTTP response headers. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.
func (*Ctx) GetRouteURL ¶
GetRouteURL generates URLs to named routes, with parameters. URLs are relative, for example: "/user/1831"
func (*Ctx) Hostname ¶
Hostname contains the hostname derived from the X-Forwarded-Host or Host HTTP header. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead. Please use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.
func (*Ctx) IP ¶
IP returns the remote IP address of the request. If ProxyHeader and IP Validation is configured, it will parse that header and return the first valid IP address. Please use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.
func (*Ctx) IPs ¶
IPs returns a string slice of IP addresses specified in the X-Forwarded-For request header. When IP validation is enabled, only valid IPs are returned.
func (*Ctx) Is ¶
Is returns the matching content type, if the incoming request's Content-Type HTTP header field matches the MIME type specified by the type parameter
func (*Ctx) IsFromLocal ¶
IsFromLocal will return true if request came from local.
func (*Ctx) IsProxyTrusted ¶
IsProxyTrusted (not implemented yet)
func (*Ctx) JSON ¶
JSON converts any interface or string to JSON. Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value. If the ctype parameter is given, this method will set the Content-Type header equal to ctype. If ctype is not given, The Content-Type header will be set to application/json.
func (*Ctx) JSONP ¶
JSONP sends a JSON response with JSONP support. This method is identical to JSON, except that it opts-in to JSONP callback support. By default, the callback name is simply callback.
func (*Ctx) Links ¶
Links joins the links followed by the property to populate the response's Link HTTP header field.
func (*Ctx) Locals ¶
Locals makes it possible to pass any values under keys scoped to the request and therefore available to all following routes that match the request.
func (*Ctx) Location ¶
Location sets the response Location HTTP header to the specified path parameter.
func (*Ctx) OriginalURL ¶
OriginalURL contains the original request URL. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting to use the value outside the Handler.
func (*Ctx) Params ¶
Params is used to get the route parameters. Defaults to empty string "" if the param doesn't exist. If a default value is given, it will return that value if the param doesn't exist. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting to use the value outside the Handler.
func (*Ctx) ParamsInt ¶
ParamsInt is used to get an integer from the route parameters it defaults to zero if the parameter is not found or if the parameter cannot be converted to an integer If a default value is given, it will return that value in case the param doesn't exist or cannot be converted to an integer
func (*Ctx) ParamsParser ¶
ParamsParser binds the param string to a struct.
func (*Ctx) Queries ¶
Queries returns a map of query parameters and their values.
GET /?name=alex&wanna_cake=2&id= Queries()["name"] == "alex" Queries()["wanna_cake"] == "2" Queries()["id"] == ""
GET /?field1=value1&field1=value2&field2=value3 Queries()["field1"] == "value2" Queries()["field2"] == "value3"
GET /?list_a=1&list_a=2&list_a=3&list_b[]=1&list_b[]=2&list_b[]=3&list_c=1,2,3 Queries()["list_a"] == "3" Queries()["list_b[]"] == "3" Queries()["list_c"] == "1,2,3"
GET /api/search?filters.author.name=John&filters.category.name=Technology&filters[customer][name]=Alice&filters[status]=pending Queries()["filters.author.name"] == "John" Queries()["filters.category.name"] == "Technology" Queries()["filters[customer][name]"] == "Alice" Queries()["filters[status]"] == "pending"
func (*Ctx) Query ¶
Query returns the query string parameter in the url. Defaults to empty string "" if the query doesn't exist. If a default value is given, it will return that value if the query doesn't exist. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting to use the value outside the Handler.
func (*Ctx) QueryBool ¶
QueryBool returns bool value of key string parameter in the url. Default to empty or invalid key is false.
Get /?name=alex&want_pizza=false&id= QueryBool("want_pizza") == false QueryBool("want_pizza", true) == false QueryBool("name") == false QueryBool("name", true) == true QueryBool("id") == false QueryBool("id", true) == true
func (*Ctx) QueryFloat ¶
QueryFloat returns float64 value of key string parameter in the url. Default to empty or invalid key is 0.
GET /?name=alex&amount=32.23&id= QueryFloat("amount") = 32.23 QueryFloat("amount", 3) = 32.23 QueryFloat("name", 1) = 1 QueryFloat("name") = 0 QueryFloat("id", 3) = 3
func (*Ctx) QueryInt ¶
QueryInt returns integer value of key string parameter in the url. Default to empty or invalid key is 0.
GET /?name=alex&wanna_cake=2&id= QueryInt("wanna_cake", 1) == 2 QueryInt("name", 1) == 1 QueryInt("id", 1) == 1 QueryInt("id") == 0
func (*Ctx) QueryParser ¶
QueryParser binds the query string to a struct.
func (*Ctx) RedirectBack ¶
RedirectBack to the URL to referer If status is not specified, status defaults to 302 Found.
func (*Ctx) RedirectToRoute ¶
RedirectToRoute to the Route registered in the app with appropriate parameters If status is not specified, status defaults to 302 Found. If you want to send queries to route, you must add "queries" key typed as map[string]string to params.
func (*Ctx) Render ¶
Render a template with data and sends a text/html response. We support the following engines: html, amber, handlebars, mustache, pug
func (*Ctx) ReqHeaderParser ¶
ReqHeaderParser binds the request header strings to a struct.
func (*Ctx) SaveFile ¶
func (*Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error
SaveFile saves any multipart file to disk.
func (*Ctx) Scheme ¶
Scheme contains the request protocol string: http or https for TLS requests. Please use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.
func (*Ctx) Send ¶
Send sets the HTTP response body without copying it. From this point onward the body argument must not be changed.
func (*Ctx) SendError ¶
SendError sends HTTP Error Use like c.SendError(fasthttp.ErrBadRequest), OR
c.SendError(fasthttp.ErrBadRequest.WithMessage("can't parse user input"))
func (*Ctx) SendStatus ¶
SendStatus sets the HTTP status code and if the response body is empty, it sets the correct status message in the body.
func (*Ctx) SendStream ¶
SendStream sets response body stream and optional body size.
func (*Ctx) SendString ¶
SendString sets the HTTP response body for string types. This means no type assertion, recommended for faster performance
func (*Ctx) SetUserContext ¶
SetUserContext sets a context implementation by user.
func (*Ctx) SetUserValues ¶
SetUserValues sets many user values using Map
func (*Ctx) Subdomains ¶
Subdomains returns a string slice of subdomains in the domain name of the request. The subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.
func (*Ctx) Type ¶
Type sets the Content-Type HTTP header to the MIME type specified by the file extension.
func (*Ctx) UserContext ¶
UserContext returns a context implementation that was set by user earlier or returns a non-nil, empty context,if it was not set earlier.
func (*Ctx) Vary ¶
Vary adds the given header field to the Vary response header. This will append the header, if not already listed, otherwise leaves it listed in the current location.
type DialFunc ¶
DialFunc must establish connection to addr.
There is no need in establishing TLS (SSL) connection for https. The client automatically converts connection to TLS if HostClient.IsTLS is set.
TCP address passed to DialFunc always contains host and port. Example TCP addr values:
- foobar.com:80
- foobar.com:443
- foobar.com:8080
type DialFuncWithTimeout ¶
DialFuncWithTimeout must establish connection to addr. Unlike DialFunc, it also accepts a timeout.
There is no need in establishing TLS (SSL) connection for https. The client automatically converts connection to TLS if HostClient.IsTLS is set.
TCP address passed to DialFuncWithTimeout always contains host and port. Example TCP addr values:
- foobar.com:80
- foobar.com:443
- foobar.com:8080
type ErrBodyStreamWritePanic ¶
type ErrBodyStreamWritePanic struct {
// contains filtered or unexported fields
}
ErrBodyStreamWritePanic is returned when panic happens during writing body stream.
type ErrBrokenChunk ¶
type ErrBrokenChunk struct {
// contains filtered or unexported fields
}
ErrBrokenChunk is returned when server receives a broken chunked body (Transfer-Encoding: chunked).
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 Error ¶
Error represents an error that occurred while handling a request.
func (Error) WithMessage ¶
WithMessage (re)sets the Error message
type ErrorHandler ¶
type ErrorHandler func(*RequestCtx, error)
type EscapeError ¶
type EscapeError string
func (EscapeError) Error ¶
func (e EscapeError) Error() string
type FS ¶
type FS struct { // FS is filesystem to serve files from. eg: embed.FS os.DirFS FS fs.FS // Path rewriting function. // // By default request path is not modified. PathRewrite PathRewriteFunc // PathNotFound fires when file is not found in filesystem // this functions tries to replace "Cannot open requested path" // server response giving to the programmer the control of server flow. // // By default PathNotFound returns // "Cannot open requested path" PathNotFound RequestHandler // Suffixes list to add to compressedFileSuffix depending on encoding // // This value has sense only if Compress is set. // // FSCompressedFileSuffixes is used by default. CompressedFileSuffixes map[string]string // If CleanStop is set, the channel can be closed to stop the cleanup handlers // for the FS RequestHandlers created with NewRequestHandler. // NEVER close this channel while the handler is still being used! CleanStop chan struct{} // Path to the root directory to serve files from. Root string // Path to the compressed root directory to serve files from. If this value // is empty, Root is used. CompressRoot string // Suffix to add to the name of cached compressed file. // // This value has sense only if Compress is set. // // FSCompressedFileSuffix is used by default. CompressedFileSuffix string // List of index file names to try opening during directory access. // // For example: // // * index.html // * index.htm // * my-super-index.xml // // By default the list is empty. IndexNames []string // Expiration duration for inactive file handlers. // // FSHandlerCacheDuration is used by default. CacheDuration time.Duration // AllowEmptyRoot controls what happens when Root is empty. When false (default) it will default to the // current working directory. An empty root is mostly useful when you want to use absolute paths // on windows that are on different filesystems. On linux setting your Root to "/" already allows you to use // absolute paths on any filesystem. AllowEmptyRoot bool // Index pages for directories without files matching IndexNames // are automatically generated if set. // // Directory index generation may be quite slow for directories // with many files (more than 1K), so it is discouraged enabling // index pages' generation for such directories. // // By default index pages aren't generated. GenerateIndexPages bool // Transparently compresses responses if set to true. // // The server tries minimizing CPU usage by caching compressed files. // It adds CompressedFileSuffix suffix to the original file name and // tries saving the resulting compressed file under the new file name. // So it is advisable to give the server write access to Root // and to all inner folders in order to minimize CPU usage when serving // compressed responses. // // Transparent compression is disabled by default. Compress bool // Uses brotli encoding and fallbacks to gzip in responses if set to true, uses gzip if set to false. // // This value has sense only if Compress is set. // // Brotli encoding is disabled by default. CompressBrotli bool // Enables byte range requests if set to true. // // Byte range requests are disabled by default. AcceptByteRange bool // SkipCache if true, will cache no file handler. // // By default is false. SkipCache bool // contains filtered or unexported fields }
FS represents settings for request handler serving static files from the local filesystem.
It is prohibited copying FS values. Create new values instead.
Example ¶
package main import ( "log" "github.com/adhocore/fasthttp" ) func main() { fs := &fasthttp.FS{ // Path to directory to serve. Root: "/var/www/static-site", // Generate index pages if client requests directory contents. GenerateIndexPages: true, // Enable transparent compression to save network traffic. Compress: true, } // Create request handler for serving static files. h := fs.NewRequestHandler() // Start the server. if err := fasthttp.ListenAndServe(":8080", h); err != nil { log.Fatalf("error in ListenAndServe: %v", err) } }
Output:
func (*FS) NewRequestHandler ¶
func (fs *FS) NewRequestHandler() RequestHandler
NewRequestHandler returns new request handler with the given FS settings.
The returned handler caches requested file handles for FS.CacheDuration. Make sure your program has enough 'max open files' limit aka 'ulimit -n' if FS.Root folder contains many files.
Do not create multiple request handlers from a single FS instance - just reuse a single request handler.
type FormValueFunc ¶
type FormValueFunc func(*RequestCtx, string) []byte
type Group ¶
type Group struct { Prefix string // contains filtered or unexported fields }
Group is route subgroup
type Handle ¶
Handle is a function that can be registered to a route to handle HTTP requests. Like HandlerFunc, but has a third parameter for the values of wildcards (path variables).
type HijackHandler ¶
HijackHandler must process the hijacked connection c.
If KeepHijackedConns is disabled, which is by default, the connection c is automatically closed after returning from HijackHandler.
The connection c must not be used after returning from the handler, if KeepHijackedConns is disabled.
When KeepHijackedConns enabled, fasthttp will not Close() the connection, you must do it when you need it. You must not use c in any way after calling Close().
type HostClient ¶
type HostClient struct { // Transport defines a transport-like mechanism that wraps every request/response. Transport RoundTripper // Callback for establishing new connections to hosts. // // Default DialTimeout is used if not set. DialTimeout DialFuncWithTimeout // Callback for establishing new connections to hosts. // // Note that if Dial is set instead of DialTimeout, Dial will ignore Request timeout. // If you want the tcp dial process to account for request timeouts, use DialTimeout instead. // // If not set, DialTimeout is used. Dial DialFunc // Optional TLS config. TLSConfig *tls.Config // RetryIf controls whether a retry should be attempted after an error. // // By default will use isIdempotent function RetryIf RetryIfFunc // Comma-separated list of upstream HTTP server host addresses, // which are passed to Dial or DialTimeout in a round-robin manner. // // Each address may contain port if default dialer is used. // For example, // // - foobar.com:80 // - foobar.com:443 // - foobar.com:8080 Addr string // Client name. Used in User-Agent request header. Name string // Maximum number of connections which may be established to all hosts // listed in Addr. // // You can change this value while the HostClient is being used // with HostClient.SetMaxConns(value) // // DefaultMaxConnsPerHost is used if not set. MaxConns int // Keep-alive connections are closed after this duration. // // By default connection duration is unlimited. MaxConnDuration time.Duration // Idle keep-alive connections are closed after this duration. // // By default idle connections are closed // after DefaultMaxIdleConnDuration. MaxIdleConnDuration time.Duration // Maximum number of attempts for idempotent calls. // // DefaultMaxIdemponentCallAttempts is used if not set. MaxIdemponentCallAttempts int // Per-connection buffer size for responses' reading. // This also limits the maximum header size. // // Default buffer size is used if 0. ReadBufferSize int // Per-connection buffer size for requests' writing. // // Default buffer size is used if 0. WriteBufferSize int // Maximum duration for full response reading (including body). // // By default response read timeout is unlimited. ReadTimeout time.Duration // Maximum duration for full request writing (including body). // // By default request write timeout is unlimited. WriteTimeout time.Duration // Maximum response body size. // // The client returns ErrBodyTooLarge if this limit is greater than 0 // and response body is greater than the limit. // // By default response body size is unlimited. MaxResponseBodySize int // Maximum duration for waiting for a free connection. // // By default will not waiting, return ErrNoFreeConns immediately MaxConnWaitTimeout time.Duration // Connection pool strategy. Can be either LIFO or FIFO (default). ConnPoolStrategy ConnPoolStrategyType // NoDefaultUserAgentHeader when set to true, causes the default // User-Agent header to be excluded from the Request. NoDefaultUserAgentHeader bool // Attempt to connect to both ipv4 and ipv6 host addresses // if set to true. // // This option is used only if default TCP dialer is used, // i.e. if Dial and DialTimeout are blank. // // By default client connects only to ipv4 addresses, // since unfortunately ipv6 remains broken in many networks worldwide :) DialDualStack bool // Whether to use TLS (aka SSL or HTTPS) for host connections. IsTLS bool // Header names are passed as-is without normalization // if this option is set. // // Disabled header names' normalization may be useful only for proxying // responses to other clients expecting case-sensitive // header names. See https://github.com/valyala/fasthttp/issues/57 // for details. // // By default request and response header names are normalized, i.e. // The first letter and the first letters following dashes // are uppercased, while all the other letters are lowercased. // Examples: // // * HOST -> Host // * content-type -> Content-Type // * cONTENT-lenGTH -> Content-Length DisableHeaderNamesNormalizing bool // 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 // Will not log potentially sensitive content in error logs. // // This option is useful for servers that handle sensitive data // in the request/response. // // Client logs full errors by default. SecureErrorLogMessage bool // StreamResponseBody enables response body streaming. StreamResponseBody bool // contains filtered or unexported fields }
HostClient balances http requests among hosts listed in Addr.
HostClient may be used for balancing load among multiple upstream hosts. While multiple addresses passed to HostClient.Addr may be used for balancing load among them, it would be better using LBClient instead, since HostClient may unevenly balance load among upstream hosts.
It is forbidden copying HostClient instances. Create new instances instead.
It is safe calling HostClient methods from concurrently running goroutines.
Example ¶
package main import ( "log" "github.com/adhocore/fasthttp" ) func main() { // Prepare a client, which fetches webpages via HTTP proxy listening // on the localhost:8080. c := &fasthttp.HostClient{ Addr: "localhost:8080", } // Fetch google page via local proxy. statusCode, body, err := c.Get(nil, "http://google.com/foo/bar") if err != nil { log.Fatalf("Error when loading google page through local proxy: %v", err) } if statusCode != fasthttp.StatusOK { log.Fatalf("Unexpected status code: %d. Expecting %d", statusCode, fasthttp.StatusOK) } useResponseBody(body) // Fetch foobar page via local proxy. Reuse body buffer. statusCode, body, err = c.Get(body, "http://foobar.com/google/com") if err != nil { log.Fatalf("Error when loading foobar page through local proxy: %v", err) } if statusCode != fasthttp.StatusOK { log.Fatalf("Unexpected status code: %d. Expecting %d", statusCode, fasthttp.StatusOK) } useResponseBody(body) } func useResponseBody(body []byte) { // Do something with body :) }
Output:
func (*HostClient) CloseIdleConnections ¶
func (c *HostClient) CloseIdleConnections()
CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.
func (*HostClient) ConnsCount ¶
func (c *HostClient) ConnsCount() int
ConnsCount returns connection count of HostClient.
func (*HostClient) Do ¶
func (c *HostClient) Do(req *Request, resp *Response) error
Do performs the given http request and sets the corresponding response.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
The function doesn't follow redirects. Use Get* for following redirects.
Response is ignored if resp is nil.
ErrNoFreeConns is returned if all HostClient.MaxConns connections to the host are busy.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func (*HostClient) DoDeadline ¶
DoDeadline performs the given request and waits for response until the given deadline.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
The function doesn't follow redirects. Use Get* for following redirects.
Response is ignored if resp is nil.
ErrTimeout is returned if the response wasn't returned until the given deadline. Immediately returns ErrTimeout if the deadline has already been reached.
ErrNoFreeConns is returned if all HostClient.MaxConns connections to the host are busy.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func (*HostClient) DoRedirects ¶
func (c *HostClient) DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error
DoRedirects performs the given http request and fills the given http response, following up to maxRedirectsCount redirects. When the redirect count exceeds maxRedirectsCount, ErrTooManyRedirects is returned.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
Client determines the server to be requested in the following order:
- from RequestURI if it contains full url with scheme and host;
- from Host header otherwise.
Response is ignored if resp is nil.
ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func (*HostClient) DoTimeout ¶
DoTimeout performs the given request and waits for response during the given timeout duration.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
The function doesn't follow redirects. Use Get* for following redirects.
Response is ignored if resp is nil.
ErrTimeout is returned if the response wasn't returned during the given timeout. Immediately returns ErrTimeout if timeout value is negative.
ErrNoFreeConns is returned if all HostClient.MaxConns connections to the host are busy.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func (*HostClient) Get ¶
Get returns the status code and body of url.
The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated.
The function follows redirects. Use Do* for manually handling redirects.
func (*HostClient) GetDeadline ¶
func (c *HostClient) GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error)
GetDeadline returns the status code and body of url.
The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated.
The function follows redirects. Use Do* for manually handling redirects.
ErrTimeout error is returned if url contents couldn't be fetched until the given deadline.
func (*HostClient) GetTimeout ¶
func (c *HostClient) GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error)
GetTimeout returns the status code and body of url.
The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated.
The function follows redirects. Use Do* for manually handling redirects.
ErrTimeout error is returned if url contents couldn't be fetched during the given timeout.
func (*HostClient) LastUseTime ¶
func (c *HostClient) LastUseTime() time.Time
LastUseTime returns time the client was last used.
func (*HostClient) PendingRequests ¶
func (c *HostClient) PendingRequests() int
PendingRequests returns the current number of requests the client is executing.
This function may be used for balancing load among multiple HostClient instances.
func (*HostClient) Post ¶
func (c *HostClient) Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error)
Post sends POST request to the given url with the given POST arguments.
The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated.
The function follows redirects. Use Do* for manually handling redirects.
Empty POST body is sent if postArgs is nil.
func (*HostClient) SetMaxConns ¶
func (c *HostClient) SetMaxConns(newMaxConns int)
SetMaxConns sets up the maximum number of connections which may be established to all hosts listed in Addr.
type InvalidHostError ¶
type InvalidHostError string
func (InvalidHostError) Error ¶
func (e InvalidHostError) Error() string
type LBClient ¶
type LBClient struct { // HealthCheck is a callback called after each request. // // The request, response and the error returned by the client // is passed to HealthCheck, so the callback may determine whether // the client is healthy. // // Load on the current client is decreased if HealthCheck returns false. // // By default HealthCheck returns false if err != nil. HealthCheck func(req *Request, resp *Response, err error) bool // Clients must contain non-zero clients list. // Incoming requests are balanced among these clients. Clients []BalancingClient // Timeout is the request timeout used when calling LBClient.Do. // // DefaultLBClientTimeout is used by default. Timeout time.Duration // contains filtered or unexported fields }
LBClient balances requests among available LBClient.Clients.
It has the following features:
- Balances load among available clients using 'least loaded' + 'least total' hybrid technique.
- Dynamically decreases load on unhealthy clients.
It is forbidden copying LBClient instances. Create new instances instead.
It is safe calling LBClient methods from concurrently running goroutines.
Example ¶
// Requests will be spread among these servers. servers := []string{ "google.com:80", "foobar.com:8080", "127.0.0.1:123", } // Prepare clients for each server var lbc fasthttp.LBClient for _, addr := range servers { c := &fasthttp.HostClient{ Addr: addr, } lbc.Clients = append(lbc.Clients, c) } // Send requests to load-balanced servers var req fasthttp.Request var resp fasthttp.Response for i := 0; i < 10; i++ { url := fmt.Sprintf("http://abcedfg/foo/bar/%d", i) req.SetRequestURI(url) if err := lbc.Do(&req, &resp); err != nil { log.Fatalf("Error when sending request: %v", err) } if resp.StatusCode() != fasthttp.StatusOK { log.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), fasthttp.StatusOK) } useResponseBody(resp.Body()) }
Output:
func (*LBClient) AddClient ¶
func (cc *LBClient) AddClient(c BalancingClient) int
AddClient adds a new client to the balanced clients and returns the new total number of clients.
func (*LBClient) Do ¶
Do calculates timeout using LBClient.Timeout and calls DoTimeout on the least loaded client.
func (*LBClient) DoDeadline ¶
DoDeadline calls DoDeadline on the least loaded client.
func (*LBClient) DoTimeout ¶
DoTimeout calculates deadline and calls DoDeadline on the least loaded client.
func (*LBClient) RemoveClients ¶
func (cc *LBClient) RemoveClients(rc func(BalancingClient) bool) int
RemoveClients removes clients using the provided callback. If rc returns true, the passed client will be removed. Returns the new total number of clients.
type Logger ¶
type Logger interface { // Printf must have the same semantics as log.Printf. Printf(format string, args ...any) }
Logger is used for logging formatted messages.
type Params ¶
type Params []Param
Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.
func ParamsFromContext ¶
ParamsFromContext pulls the URL parameters from a request context, or returns nil if none are present.
type PathRewriteFunc ¶
type PathRewriteFunc func(ctx *RequestCtx) []byte
PathRewriteFunc must return new request path based on arbitrary ctx info such as ctx.Path().
Path rewriter is used in FS for translating the current request to the local filesystem path relative to FS.Root.
The returned path must not contain '/../' substrings due to security reasons, since such paths may refer files outside FS.Root.
The returned path may refer to ctx members. For example, ctx.Path().
func NewPathPrefixStripper ¶
func NewPathPrefixStripper(prefixSize int) PathRewriteFunc
NewPathPrefixStripper returns path rewriter, which removes prefixSize bytes from the path prefix.
Examples:
- prefixSize = 0, original path: "/foo/bar", result: "/foo/bar"
- prefixSize = 3, original path: "/foo/bar", result: "o/bar"
- prefixSize = 7, original path: "/foo/bar", result: "r"
The returned path rewriter may be used as FS.PathRewrite .
func NewPathSlashesStripper ¶
func NewPathSlashesStripper(slashesCount int) PathRewriteFunc
NewPathSlashesStripper returns path rewriter, which strips slashesCount leading slashes from the path.
Examples:
- slashesCount = 0, original path: "/foo/bar", result: "/foo/bar"
- slashesCount = 1, original path: "/foo/bar", result: "/bar"
- slashesCount = 2, original path: "/foo/bar", result: ""
The returned path rewriter may be used as FS.PathRewrite .
func NewVHostPathRewriter ¶
func NewVHostPathRewriter(slashesCount int) PathRewriteFunc
NewVHostPathRewriter returns path rewriter, which strips slashesCount leading slashes from the path and prepends the path with request's host, thus simplifying virtual hosting for static files.
Examples:
host=foobar.com, slashesCount=0, original path="/foo/bar". Resulting path: "/foobar.com/foo/bar"
host=img.aaa.com, slashesCount=1, original path="/images/123/456.jpg" Resulting path: "/img.aaa.com/123/456.jpg"
type PipelineClient ¶
type PipelineClient struct { // Logger for logging client errors. // // By default standard logger from log package is used. Logger Logger // Callback for connection establishing to the host. // // Default Dial is used if not set. Dial DialFunc // Optional TLS config. TLSConfig *tls.Config // Address of the host to connect to. Addr string // PipelineClient name. Used in User-Agent request header. Name string // The maximum number of concurrent connections to the Addr. // // A single connection is used by default. MaxConns int // The maximum number of pending pipelined requests over // a single connection to Addr. // // DefaultMaxPendingRequests is used by default. MaxPendingRequests int // The maximum delay before sending pipelined requests as a batch // to the server. // // By default requests are sent immediately to the server. MaxBatchDelay time.Duration // Idle connection to the host is closed after this duration. // // By default idle connection is closed after // DefaultMaxIdleConnDuration. MaxIdleConnDuration time.Duration // Buffer size for responses' reading. // This also limits the maximum header size. // // Default buffer size is used if 0. ReadBufferSize int // Buffer size for requests' writing. // // Default buffer size is used if 0. WriteBufferSize int // Maximum duration for full response reading (including body). // // By default response read timeout is unlimited. ReadTimeout time.Duration // Maximum duration for full request writing (including body). // // By default request write timeout is unlimited. WriteTimeout time.Duration // NoDefaultUserAgentHeader when set to true, causes the default // User-Agent header to be excluded from the Request. NoDefaultUserAgentHeader bool // Attempt to connect to both ipv4 and ipv6 host addresses // if set to true. // // This option is used only if default TCP dialer is used, // i.e. if Dial is blank. // // By default client connects only to ipv4 addresses, // since unfortunately ipv6 remains broken in many networks worldwide :) DialDualStack bool // Response header names are passed as-is without normalization // if this option is set. // // Disabled header names' normalization may be useful only for proxying // responses to other clients expecting case-sensitive // header names. See https://github.com/valyala/fasthttp/issues/57 // for details. // // By default request and response header names are normalized, i.e. // The first letter and the first letters following dashes // are uppercased, while all the other letters are lowercased. // Examples: // // * HOST -> Host // * content-type -> Content-Type // * cONTENT-lenGTH -> Content-Length DisableHeaderNamesNormalizing bool // 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 // Whether to use TLS (aka SSL or HTTPS) for host connections. IsTLS bool // contains filtered or unexported fields }
PipelineClient pipelines requests over a limited set of concurrent connections to the given Addr.
This client may be used in highly loaded HTTP-based RPC systems for reducing context switches and network level overhead. See https://en.wikipedia.org/wiki/HTTP_pipelining for details.
It is forbidden copying PipelineClient instances. Create new instances instead.
It is safe calling PipelineClient methods from concurrently running goroutines.
func (*PipelineClient) Do ¶
func (c *PipelineClient) Do(req *Request, resp *Response) error
Do performs the given http request and sets the corresponding response.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
The function doesn't follow redirects. Use Get* for following redirects.
Response is ignored if resp is nil.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func (*PipelineClient) DoDeadline ¶
DoDeadline performs the given request and waits for response until the given deadline.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
The function doesn't follow redirects.
Response is ignored if resp is nil.
ErrTimeout is returned if the response wasn't returned until the given deadline.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func (*PipelineClient) DoTimeout ¶
DoTimeout performs the given request and waits for response during the given timeout duration.
Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI.
The function doesn't follow redirects.
Response is ignored if resp is nil.
ErrTimeout is returned if the response wasn't returned during the given timeout.
It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
func (*PipelineClient) PendingRequests ¶
func (c *PipelineClient) PendingRequests() int
PendingRequests returns the current number of pending requests pipelined to the server.
This number may exceed MaxPendingRequests*MaxConns by up to two times, since each connection to the server may keep up to MaxPendingRequests requests in the queue before sending them to the server.
This function may be used for balancing load among multiple PipelineClient instances.
type ReadCloserWithError ¶
type Render ¶
type Render struct { Directory string Extension string Reload bool // contains filtered or unexported fields }
type Request ¶
type Request struct { // Request header. // // Copying Header by value is forbidden. Use pointer to Header instead. Header RequestHeader // Use Host header (request.Header.SetHost) instead of the host from SetRequestURI, SetHost, or URI().SetHost UseHostHeader bool // DisableRedirectPathNormalizing disables redirect path normalization when used with DoRedirects. // // By default redirect path values are normalized, i.e. // extra slashes are removed, special characters are encoded. DisableRedirectPathNormalizing bool // contains filtered or unexported fields }
Request represents HTTP request.
It is forbidden copying Request instances. Create new instances and use CopyTo instead.
Request instance MUST NOT be used from concurrently running goroutines.
func AcquireRequest ¶
func AcquireRequest() *Request
AcquireRequest returns an empty Request instance from request pool.
The returned Request instance may be passed to ReleaseRequest when it is no longer needed. This allows Request recycling, reduces GC pressure and usually improves performance.
func (*Request) AppendBody ¶
AppendBody appends p to request body.
It is safe re-using p after the function returns.
func (*Request) AppendBodyString ¶
AppendBodyString appends s to request body.
func (*Request) Body ¶
Body returns request body.
The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead.
func (*Request) BodyGunzip ¶
BodyGunzip returns un-gzipped body data.
This method may be used if the request header contains 'Content-Encoding: gzip' for reading un-gzipped body. Use Body for reading gzipped request body.
func (*Request) BodyInflate ¶
BodyInflate returns inflated body data.
This method may be used if the response header contains 'Content-Encoding: deflate' for reading inflated request body. Use Body for reading deflated request body.
func (*Request) BodyStream ¶
BodyStream returns io.Reader.
You must CloseBodyStream or ReleaseRequest after you use it.
func (*Request) BodyUncompressed ¶
BodyUncompressed returns body data and if needed decompress it from gzip, deflate or Brotli.
This method may be used if the response header contains 'Content-Encoding' for reading uncompressed request body. Use Body for reading the raw request body.
func (*Request) BodyWriteTo ¶
BodyWriteTo writes request body to w.
func (*Request) BodyWriter ¶
BodyWriter returns writer for populating request body.
func (*Request) CloseBodyStream ¶
func (*Request) ConnectionClose ¶
ConnectionClose returns true if 'Connection: close' header is set.
func (*Request) ContinueReadBody ¶
func (req *Request) ContinueReadBody(r *bufio.Reader, maxBodySize int, preParseMultipartForm ...bool) error
ContinueReadBody reads request body if request header contains 'Expect: 100-continue'.
The caller must send StatusContinue response before calling this method.
If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned.
func (*Request) ContinueReadBodyStream ¶
func (req *Request) ContinueReadBodyStream(r *bufio.Reader, maxBodySize int, preParseMultipartForm ...bool) error
ContinueReadBodyStream reads request body if request header contains 'Expect: 100-continue'.
The caller must send StatusContinue response before calling this method.
If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned.
func (*Request) IsBodyStream ¶
IsBodyStream returns true if body is set via SetBodyStream*.
func (*Request) MayContinue ¶
MayContinue returns true if the request contains 'Expect: 100-continue' header.
The caller must do one of the following actions if MayContinue returns true:
- Either send StatusExpectationFailed response if request headers don't satisfy the caller.
- Or send StatusContinue response before reading request body with ContinueReadBody.
- Or close the connection.
func (*Request) MultipartForm ¶
MultipartForm returns request's multipart form.
Returns ErrNoMultipartForm if request's Content-Type isn't 'multipart/form-data'.
RemoveMultipartFormFiles must be called after returned multipart form is processed.
func (*Request) Read ¶
Read reads request (including body) from the given r.
RemoveMultipartFormFiles or Reset must be called after reading multipart/form-data request in order to delete temporarily uploaded files.
If MayContinue returns true, the caller must:
- Either send StatusExpectationFailed response if request headers don't satisfy the caller.
- Or send StatusContinue response before reading request body with ContinueReadBody.
- Or close the connection.
io.EOF is returned if r is closed before reading the first header byte.
func (*Request) ReadBody ¶
ReadBody reads request body from the given r, limiting the body size.
If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned.
func (*Request) ReadLimitBody ¶
ReadLimitBody reads request from the given r, limiting the body size.
If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned.
RemoveMultipartFormFiles or Reset must be called after reading multipart/form-data request in order to delete temporarily uploaded files.
If MayContinue returns true, the caller must:
- Either send StatusExpectationFailed response if request headers don't satisfy the caller.
- Or send StatusContinue response before reading request body with ContinueReadBody.
- Or close the connection.
io.EOF is returned if r is closed before reading the first header byte.
func (*Request) ReleaseBody ¶
ReleaseBody retires the request body if it is greater than "size" bytes.
This permits GC to reclaim the large buffer. If used, must be before ReleaseRequest.
Use this method only if you really understand how it works. The majority of workloads don't need this method.
func (*Request) RemoveMultipartFormFiles ¶
func (req *Request) RemoveMultipartFormFiles()
RemoveMultipartFormFiles removes multipart/form-data temporary files associated with the request.
func (*Request) RequestURI ¶
RequestURI returns request's URI.
func (*Request) SetBody ¶
SetBody sets request body.
It is safe re-using body argument after the function returns.
func (*Request) SetBodyRaw ¶
SetBodyRaw sets response body, but without copying it.
From this point onward the body argument must not be changed.
func (*Request) SetBodyStream ¶
SetBodyStream sets request body stream and, optionally body size.
If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes before returning io.EOF.
If bodySize < 0, then bodyStream is read until io.EOF.
bodyStream.Close() is called after finishing reading all body data if it implements io.Closer.
Note that GET and HEAD requests cannot have body.
See also SetBodyStreamWriter.
func (*Request) SetBodyStreamWriter ¶
func (req *Request) SetBodyStreamWriter(sw StreamWriter)
SetBodyStreamWriter registers the given sw for populating request body.
This function may be used in the following cases:
- if request body is too big (more than 10MB).
- if request body is streamed from slow external sources.
- if request body must be streamed to the server in chunks (aka `http client push` or `chunked transfer-encoding`).
Note that GET and HEAD requests cannot have body.
See also SetBodyStream.
func (*Request) SetBodyString ¶
SetBodyString sets request body.
func (*Request) SetConnectionClose ¶
func (req *Request) SetConnectionClose()
SetConnectionClose sets 'Connection: close' header.
func (*Request) SetHostBytes ¶
SetHostBytes sets host for the request.
func (*Request) SetRequestURI ¶
SetRequestURI sets RequestURI.
func (*Request) SetRequestURIBytes ¶
SetRequestURIBytes sets RequestURI.
func (*Request) SetTimeout ¶
SetTimeout sets timeout for the request.
The following code:
req.SetTimeout(t) c.Do(&req, &resp)
is equivalent to
c.DoTimeout(&req, &resp, t)
func (*Request) SetURI ¶
SetURI initializes request URI. Use this method if a single URI may be reused across multiple requests. Otherwise, you can just use SetRequestURI() and it will be parsed as new URI. The URI is copied and can be safely modified later.
func (*Request) String ¶
String returns request representation.
Returns error message instead of request representation on error.
Use Write instead of String for performance-critical code.
func (*Request) SwapBody ¶
SwapBody swaps request body with the given body and returns the previous request body.
It is forbidden to use the body passed to SwapBody after the function returns.
type RequestConfig ¶
type RequestConfig struct { // ReadTimeout is the maximum duration for reading the entire // request body. // A zero value means that default values will be honored. ReadTimeout time.Duration // WriteTimeout is the maximum duration before timing out // writes of the response. // A zero value means that default values will be honored. WriteTimeout time.Duration // Maximum request body size. // A zero value means that default values will be honored. MaxRequestBodySize int }
RequestConfig configure the per request deadline and body limits.
type RequestCtx ¶
type RequestCtx struct { // Outgoing response. // // Copying Response by value is forbidden. Use pointer to Response instead. Response Response // Incoming request. // // Copying Request by value is forbidden. Use pointer to Request instead. Request Request // contains filtered or unexported fields }
RequestCtx contains incoming request and manages outgoing response.
It is forbidden copying RequestCtx instances.
RequestHandler should avoid holding references to incoming RequestCtx and/or its members after the return. If holding RequestCtx references after the return is unavoidable (for instance, ctx is passed to a separate goroutine and ctx lifetime cannot be controlled), then the RequestHandler MUST call ctx.TimeoutError() before return.
It is unsafe modifying/reading RequestCtx instance from concurrently running goroutines. The only exception is TimeoutError*, which may be called while other goroutines accessing RequestCtx.
func (*RequestCtx) Conn ¶
func (ctx *RequestCtx) Conn() net.Conn
Conn returns a reference to the underlying net.Conn.
WARNING: Only use this method if you know what you are doing!
Reading from or writing to the returned connection will end badly!
func (*RequestCtx) ConnID ¶
func (ctx *RequestCtx) ConnID() uint64
ConnID returns unique connection ID.
This ID may be used to match distinct requests to the same incoming connection.
func (*RequestCtx) ConnRequestNum ¶
func (ctx *RequestCtx) ConnRequestNum() uint64
ConnRequestNum returns request sequence number for the current connection.
Sequence starts with 1.
func (*RequestCtx) ConnTime ¶
func (ctx *RequestCtx) ConnTime() time.Time
ConnTime returns the time the server started serving the connection the current request came from.
func (*RequestCtx) Deadline ¶
func (ctx *RequestCtx) Deadline() (deadline time.Time, ok bool)
Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results.
This method always returns 0, false and is only present to make RequestCtx implement the context interface.
func (*RequestCtx) Done ¶
func (ctx *RequestCtx) Done() <-chan struct{}
Done returns a channel that's closed when work done on behalf of this context should be canceled. Done may return nil if this context can never be canceled. Successive calls to Done return the same value.
Note: Because creating a new channel for every request is just too expensive, so RequestCtx.s.done is only closed when the server is shutting down.
func (*RequestCtx) Err ¶
func (ctx *RequestCtx) Err() error
Err returns a non-nil error value after Done is closed, successive calls to Err return the same error. If Done is not yet closed, Err returns nil. If Done is closed, Err returns a non-nil error explaining why: Canceled if the context was canceled (via server Shutdown) or DeadlineExceeded if the context's deadline passed.
Note: Because creating a new channel for every request is just too expensive, so RequestCtx.s.done is only closed when the server is shutting down.
func (*RequestCtx) Error ¶
func (ctx *RequestCtx) Error(msg string, statusCode int)
Error sets response status code to the given value and sets response body to the given message.
Warning: this will reset the response headers and body already set!
func (*RequestCtx) FormFile ¶
func (ctx *RequestCtx) FormFile(key string) (*multipart.FileHeader, error)
FormFile returns uploaded file associated with the given multipart form key.
The file is automatically deleted after returning from RequestHandler, so either move or copy uploaded file into new place if you want retaining it.
Use SaveMultipartFile function for permanently saving uploaded file.
The returned file header is valid until your request handler returns.
func (*RequestCtx) FormValue ¶
func (ctx *RequestCtx) FormValue(key string) []byte
FormValue returns form value associated with the given key.
The value is searched in the following places:
- Query string.
- POST or PUT body.
There are more fine-grained methods for obtaining form values:
- QueryArgs for obtaining values from query string.
- PostArgs for obtaining values from POST or PUT body.
- MultipartForm for obtaining values from multipart form.
- FormFile for obtaining uploaded files.
The returned value is valid until your request handler returns.
func (*RequestCtx) Hijack ¶
func (ctx *RequestCtx) Hijack(handler HijackHandler)
Hijack registers the given handler for connection hijacking.
The handler is called after returning from RequestHandler and sending http response. The current connection is passed to the handler. The connection is automatically closed after returning from the handler.
The server skips calling the handler in the following cases:
- 'Connection: close' header exists in either request or response.
- Unexpected error during response writing to the connection.
The server stops processing requests from hijacked connections.
Server limits such as Concurrency, ReadTimeout, WriteTimeout, etc. aren't applied to hijacked connections.
The handler must not retain references to ctx members.
Arbitrary 'Connection: Upgrade' protocols may be implemented with HijackHandler. For instance,
- WebSocket ( https://en.wikipedia.org/wiki/WebSocket )
- HTTP/2.0 ( https://en.wikipedia.org/wiki/HTTP/2 )
Example ¶
package main import ( "fmt" "log" "net" "github.com/adhocore/fasthttp" ) func main() { // hijackHandler is called on hijacked connection. hijackHandler := func(c net.Conn) { fmt.Fprintf(c, "This message is sent over a hijacked connection to the client %s\n", c.RemoteAddr()) fmt.Fprintf(c, "Send me something and I'll echo it to you\n") var buf [1]byte for { if _, err := c.Read(buf[:]); err != nil { log.Printf("error when reading from hijacked connection: %v", err) return } fmt.Fprintf(c, "You sent me %q. Waiting for new data\n", buf[:]) } } // requestHandler is called for each incoming request. requestHandler := func(ctx *fasthttp.RequestCtx) { path := ctx.Path() switch { case string(path) == "/hijack": // Note that the connection is hijacked only after // returning from requestHandler and sending http response. ctx.Hijack(hijackHandler) // The connection will be hijacked after sending this response. fmt.Fprintf(ctx, "Hijacked the connection!") case string(path) == "/": fmt.Fprintf(ctx, "Root directory requested") default: fmt.Fprintf(ctx, "Requested path is %q", path) } } if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil { log.Fatalf("error in ListenAndServe: %v", err) } }
Output:
func (*RequestCtx) HijackSetNoResponse ¶
func (ctx *RequestCtx) HijackSetNoResponse(noResponse bool)
HijackSetNoResponse changes the behavior of hijacking a request. If HijackSetNoResponse is called with false fasthttp will send a response to the client before calling the HijackHandler (default). If HijackSetNoResponse is called with true no response is send back before calling the HijackHandler supplied in the Hijack function.
func (*RequestCtx) Hijacked ¶
func (ctx *RequestCtx) Hijacked() bool
Hijacked returns true after Hijack is called.
func (*RequestCtx) Host ¶
func (ctx *RequestCtx) Host() []byte
Host returns requested host.
The returned bytes are valid until your request handler returns.
func (*RequestCtx) IfModifiedSince ¶
func (ctx *RequestCtx) IfModifiedSince(lastModified time.Time) bool
IfModifiedSince returns true if lastModified exceeds 'If-Modified-Since' value from the request header.
The function returns true also 'If-Modified-Since' request header is missing.
func (*RequestCtx) Init ¶
func (ctx *RequestCtx) Init(req *Request, remoteAddr net.Addr, logger Logger)
Init prepares ctx for passing to RequestHandler.
remoteAddr and logger are optional. They are used by RequestCtx.Logger().
This function is intended for custom Server implementations.
func (*RequestCtx) Init2 ¶
func (ctx *RequestCtx) Init2(conn net.Conn, logger Logger, reduceMemoryUsage bool)
Init2 prepares ctx for passing to RequestHandler.
conn is used only for determining local and remote addresses.
This function is intended for custom Server implementations. See https://github.com/valyala/httpteleport for details.
func (*RequestCtx) IsBodyStream ¶
func (ctx *RequestCtx) IsBodyStream() bool
IsBodyStream returns true if response body is set via SetBodyStream*.
func (*RequestCtx) IsConnect ¶
func (ctx *RequestCtx) IsConnect() bool
IsConnect returns true if request method is CONNECT.
func (*RequestCtx) IsDelete ¶
func (ctx *RequestCtx) IsDelete() bool
IsDelete returns true if request method is DELETE.
func (*RequestCtx) IsGet ¶
func (ctx *RequestCtx) IsGet() bool
IsGet returns true if request method is GET.
func (*RequestCtx) IsHead ¶
func (ctx *RequestCtx) IsHead() bool
IsHead returns true if request method is HEAD.
func (*RequestCtx) IsOptions ¶
func (ctx *RequestCtx) IsOptions() bool
IsOptions returns true if request method is OPTIONS.
func (*RequestCtx) IsPatch ¶
func (ctx *RequestCtx) IsPatch() bool
IsPatch returns true if request method is PATCH.
func (*RequestCtx) IsPost ¶
func (ctx *RequestCtx) IsPost() bool
IsPost returns true if request method is POST.
func (*RequestCtx) IsPut ¶
func (ctx *RequestCtx) IsPut() bool
IsPut returns true if request method is PUT.
func (*RequestCtx) IsTLS ¶
func (ctx *RequestCtx) IsTLS() bool
IsTLS returns true if the underlying connection is tls.Conn.
tls.Conn is an encrypted connection (aka SSL, HTTPS).
func (*RequestCtx) IsTrace ¶
func (ctx *RequestCtx) IsTrace() bool
IsTrace returns true if request method is TRACE.
func (*RequestCtx) LastTimeoutErrorResponse ¶
func (ctx *RequestCtx) LastTimeoutErrorResponse() *Response
LastTimeoutErrorResponse returns the last timeout response set via TimeoutError* call.
This function is intended for custom server implementations.
func (*RequestCtx) LocalAddr ¶
func (ctx *RequestCtx) LocalAddr() net.Addr
LocalAddr returns server address for the given request.
Always returns non-nil result.
func (*RequestCtx) LocalIP ¶
func (ctx *RequestCtx) LocalIP() net.IP
LocalIP returns the server ip the request came to.
Always returns non-nil result.
func (*RequestCtx) Logger ¶
func (ctx *RequestCtx) Logger() Logger
Logger returns logger, which may be used for logging arbitrary request-specific messages inside RequestHandler.
Each message logged via returned logger contains request-specific information such as request id, request duration, local address, remote address, request method and request url.
It is safe re-using returned logger for logging multiple messages for the current request.
The returned logger is valid until your request handler returns.
Example ¶
package main import ( "fmt" "log" "github.com/adhocore/fasthttp" ) func main() { requestHandler := func(ctx *fasthttp.RequestCtx) { if string(ctx.Path()) == "/top-secret" { ctx.Logger().Printf("Alarm! Alien intrusion detected!") ctx.Error("Access denied!", fasthttp.StatusForbidden) return } // Logger may be cached in local variables. logger := ctx.Logger() logger.Printf("Good request from User-Agent %q", ctx.Request.Header.UserAgent()) fmt.Fprintf(ctx, "Good request to %q", ctx.Path()) logger.Printf("Multiple log messages may be written during a single request") } if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil { log.Fatalf("error in ListenAndServe: %v", err) } }
Output:
func (*RequestCtx) Method ¶
func (ctx *RequestCtx) Method() []byte
Method return request method.
Returned value is valid until your request handler returns.
func (*RequestCtx) MultipartForm ¶
func (ctx *RequestCtx) MultipartForm() (*multipart.Form, error)
MultipartForm returns request's multipart form.
Returns ErrNoMultipartForm if request's content-type isn't 'multipart/form-data'.
All uploaded temporary files are automatically deleted after returning from RequestHandler. Either move or copy uploaded files into new place if you want retaining them.
Use SaveMultipartFile function for permanently saving uploaded file.
The returned form is valid until your request handler returns.
See also FormFile and FormValue.
func (*RequestCtx) NotFound ¶
func (ctx *RequestCtx) NotFound()
NotFound resets response and sets '404 Not Found' response status code.
func (*RequestCtx) NotModified ¶
func (ctx *RequestCtx) NotModified()
NotModified resets response and sets '304 Not Modified' response status code.
func (*RequestCtx) Path ¶
func (ctx *RequestCtx) Path() []byte
Path returns requested path.
The returned bytes are valid until your request handler returns.
func (*RequestCtx) PostArgs ¶
func (ctx *RequestCtx) PostArgs() *Args
PostArgs returns POST arguments.
It doesn't return query arguments from RequestURI - use QueryArgs for this.
See also QueryArgs, FormValue and FormFile.
These args are valid until your request handler returns.
func (*RequestCtx) PostBody ¶
func (ctx *RequestCtx) PostBody() []byte
PostBody returns POST request body.
The returned bytes are valid until your request handler returns.
func (*RequestCtx) QueryArgs ¶
func (ctx *RequestCtx) QueryArgs() *Args
QueryArgs returns query arguments from RequestURI.
It doesn't return POST'ed arguments - use PostArgs() for this.
See also PostArgs, FormValue and FormFile.
These args are valid until your request handler returns.
func (*RequestCtx) Redirect ¶
func (ctx *RequestCtx) Redirect(uri string, statusCode int)
Redirect sets 'Location: uri' response header and sets the given statusCode.
statusCode must have one of the following values:
- StatusMovedPermanently (301)
- StatusFound (302)
- StatusSeeOther (303)
- StatusTemporaryRedirect (307)
- StatusPermanentRedirect (308)
All other statusCode values are replaced by StatusFound (302).
The redirect uri may be either absolute or relative to the current request uri. Fasthttp will always send an absolute uri back to the client. To send a relative uri you can use the following code:
strLocation = []byte("Location") // Put this with your top level var () declarations. ctx.Response.Header.SetCanonical(strLocation, "/relative?uri") ctx.Response.SetStatusCode(fasthttp.StatusMovedPermanently)
func (*RequestCtx) RedirectBytes ¶
func (ctx *RequestCtx) RedirectBytes(uri []byte, statusCode int)
RedirectBytes sets 'Location: uri' response header and sets the given statusCode.
statusCode must have one of the following values:
- StatusMovedPermanently (301)
- StatusFound (302)
- StatusSeeOther (303)
- StatusTemporaryRedirect (307)
- StatusPermanentRedirect (308)
All other statusCode values are replaced by StatusFound (302).
The redirect uri may be either absolute or relative to the current request uri. Fasthttp will always send an absolute uri back to the client. To send a relative uri you can use the following code:
strLocation = []byte("Location") // Put this with your top level var () declarations. ctx.Response.Header.SetCanonical(strLocation, "/relative?uri") ctx.Response.SetStatusCode(fasthttp.StatusMovedPermanently)
func (*RequestCtx) Referer ¶
func (ctx *RequestCtx) Referer() []byte
Referer returns request referer.
The returned bytes are valid until your request handler returns.
func (*RequestCtx) RemoteAddr ¶
func (ctx *RequestCtx) RemoteAddr() net.Addr
RemoteAddr returns client address for the given request.
Always returns non-nil result.
func (*RequestCtx) RemoteIP ¶
func (ctx *RequestCtx) RemoteIP() net.IP
RemoteIP returns the client ip the request came from.
Always returns non-nil result.
func (*RequestCtx) RemoveUserValue ¶
func (ctx *RequestCtx) RemoveUserValue(key any)
RemoveUserValue removes the given key and the value under it in ctx.
func (*RequestCtx) RemoveUserValueBytes ¶
func (ctx *RequestCtx) RemoveUserValueBytes(key []byte)
RemoveUserValueBytes removes the given key and the value under it in ctx.
func (*RequestCtx) RequestBodyStream ¶
func (ctx *RequestCtx) RequestBodyStream() io.Reader
func (*RequestCtx) RequestURI ¶
func (ctx *RequestCtx) RequestURI() []byte
RequestURI returns RequestURI.
The returned bytes are valid until your request handler returns.
func (*RequestCtx) ResetBody ¶
func (ctx *RequestCtx) ResetBody()
ResetBody resets response body contents.
func (*RequestCtx) ResetUserValues ¶
func (ctx *RequestCtx) ResetUserValues()
ResetUserValues allows to reset user values from Request Context.
func (*RequestCtx) SendFile ¶
func (ctx *RequestCtx) SendFile(path string)
SendFile sends local file contents from the given path as response body.
This is a shortcut to ServeFile(ctx, path).
SendFile logs all the errors via ctx.Logger.
See also ServeFile, FSHandler and FS.
WARNING: do not pass any user supplied paths to this function! WARNING: if path is based on user input users will be able to request any file on your filesystem! Use fasthttp.FS with a sane Root instead.
func (*RequestCtx) SendFileBytes ¶
func (ctx *RequestCtx) SendFileBytes(path []byte)
SendFileBytes sends local file contents from the given path as response body.
This is a shortcut to ServeFileBytes(ctx, path).
SendFileBytes logs all the errors via ctx.Logger.
See also ServeFileBytes, FSHandler and FS.
WARNING: do not pass any user supplied paths to this function! WARNING: if path is based on user input users will be able to request any file on your filesystem! Use fasthttp.FS with a sane Root instead.
func (*RequestCtx) SetBody ¶
func (ctx *RequestCtx) SetBody(body []byte)
SetBody sets response body to the given value.
It is safe re-using body argument after the function returns.
func (*RequestCtx) SetBodyStream ¶
func (ctx *RequestCtx) SetBodyStream(bodyStream io.Reader, bodySize int)
SetBodyStream sets response body stream and, optionally body size.
bodyStream.Close() is called after finishing reading all body data if it implements io.Closer.
If bodySize is >= 0, then bodySize bytes must be provided by bodyStream before returning io.EOF.
If bodySize < 0, then bodyStream is read until io.EOF.
See also SetBodyStreamWriter.
func (*RequestCtx) SetBodyStreamWriter ¶
func (ctx *RequestCtx) SetBodyStreamWriter(sw StreamWriter)
SetBodyStreamWriter registers the given stream writer for populating response body.
Access to RequestCtx and/or its members is forbidden from sw.
This function may be used in the following cases:
- if response body is too big (more than 10MB).
- if response body is streamed from slow external sources.
- if response body must be streamed to the client in chunks. (aka `http server push`).
Example ¶
package main import ( "bufio" "fmt" "log" "time" "github.com/adhocore/fasthttp" ) func main() { // Start fasthttp server for streaming responses. if err := fasthttp.ListenAndServe(":8080", responseStreamHandler); err != nil { log.Fatalf("unexpected error in server: %v", err) } } func responseStreamHandler(ctx *fasthttp.RequestCtx) { // Send the response in chunks and wait for a second between each chunk. ctx.SetBodyStreamWriter(func(w *bufio.Writer) { for i := 0; i < 10; i++ { fmt.Fprintf(w, "this is a message number %d", i) // Do not forget flushing streamed data to the client. if err := w.Flush(); err != nil { return } time.Sleep(time.Second) } }) }
Output:
func (*RequestCtx) SetBodyString ¶
func (ctx *RequestCtx) SetBodyString(body string)
SetBodyString sets response body to the given value.
func (*RequestCtx) SetConnectionClose ¶
func (ctx *RequestCtx) SetConnectionClose()
SetConnectionClose sets 'Connection: close' response header and closes connection after the RequestHandler returns.
func (*RequestCtx) SetContentType ¶
func (ctx *RequestCtx) SetContentType(contentType string)
SetContentType sets response Content-Type.
func (*RequestCtx) SetContentTypeBytes ¶
func (ctx *RequestCtx) SetContentTypeBytes(contentType []byte)
SetContentTypeBytes sets response Content-Type.
It is safe modifying contentType buffer after function return.
func (*RequestCtx) SetRemoteAddr ¶
func (ctx *RequestCtx) SetRemoteAddr(remoteAddr net.Addr)
SetRemoteAddr sets remote address to the given value.
Set nil value to restore default behaviour for using connection remote address.
func (*RequestCtx) SetStatusCode ¶
func (ctx *RequestCtx) SetStatusCode(statusCode int)
SetStatusCode sets response status code.
func (*RequestCtx) SetUserValue ¶
func (ctx *RequestCtx) SetUserValue(key, value any)
SetUserValue stores the given value (arbitrary object) under the given key in ctx.
The value stored in ctx may be obtained by UserValue*.
This functionality may be useful for passing arbitrary values between functions involved in request processing.
All the values are removed from ctx after returning from the top RequestHandler. Additionally, Close method is called on each value implementing io.Closer before removing the value from ctx.
func (*RequestCtx) SetUserValueBytes ¶
func (ctx *RequestCtx) SetUserValueBytes(key []byte, value any)
SetUserValueBytes stores the given value (arbitrary object) under the given key in ctx.
The value stored in ctx may be obtained by UserValue*.
This functionality may be useful for passing arbitrary values between functions involved in request processing.
All the values stored in ctx are deleted after returning from RequestHandler.
func (*RequestCtx) String ¶
func (ctx *RequestCtx) String() string
String returns unique string representation of the ctx.
The returned value may be useful for logging.
func (*RequestCtx) Success ¶
func (ctx *RequestCtx) Success(contentType string, body []byte)
Success sets response Content-Type and body to the given values.
func (*RequestCtx) SuccessString ¶
func (ctx *RequestCtx) SuccessString(contentType, body string)
SuccessString sets response Content-Type and body to the given values.
func (*RequestCtx) TLSConnectionState ¶
func (ctx *RequestCtx) TLSConnectionState() *tls.ConnectionState
TLSConnectionState returns TLS connection state.
The function returns nil if the underlying connection isn't tls.Conn.
The returned state may be used for verifying TLS version, client certificates, etc.
func (*RequestCtx) Time ¶
func (ctx *RequestCtx) Time() time.Time
Time returns RequestHandler call time.
func (*RequestCtx) TimeoutError ¶
func (ctx *RequestCtx) TimeoutError(msg string)
TimeoutError sets response status code to StatusRequestTimeout and sets body to the given msg.
All response modifications after TimeoutError call are ignored.
TimeoutError MUST be called before returning from RequestHandler if there are references to ctx and/or its members in other goroutines remain.
Usage of this function is discouraged. Prefer eliminating ctx references from pending goroutines instead of using this function.
Example ¶
package main import ( "fmt" "log" "math/rand" "time" "github.com/adhocore/fasthttp" ) func main() { requestHandler := func(ctx *fasthttp.RequestCtx) { // Emulate long-running task, which touches ctx. doneCh := make(chan struct{}) go func() { workDuration := time.Millisecond * time.Duration(rand.Intn(2000)) time.Sleep(workDuration) fmt.Fprintf(ctx, "ctx has been accessed by long-running task\n") fmt.Fprintf(ctx, "The requestHandler may be finished by this time.\n") close(doneCh) }() select { case <-doneCh: fmt.Fprintf(ctx, "The task has been finished in less than a second") case <-time.After(time.Second): // Since the long-running task is still running and may access ctx, // we must call TimeoutError before returning from requestHandler. // // Otherwise the program will suffer from data races. ctx.TimeoutError("Timeout!") } } if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil { log.Fatalf("error in ListenAndServe: %v", err) } }
Output:
func (*RequestCtx) TimeoutErrorWithCode ¶
func (ctx *RequestCtx) TimeoutErrorWithCode(msg string, statusCode int)
TimeoutErrorWithCode sets response body to msg and response status code to statusCode.
All response modifications after TimeoutErrorWithCode call are ignored.
TimeoutErrorWithCode MUST be called before returning from RequestHandler if there are references to ctx and/or its members in other goroutines remain.
Usage of this function is discouraged. Prefer eliminating ctx references from pending goroutines instead of using this function.
func (*RequestCtx) TimeoutErrorWithResponse ¶
func (ctx *RequestCtx) TimeoutErrorWithResponse(resp *Response)
TimeoutErrorWithResponse marks the ctx as timed out and sends the given response to the client.
All ctx modifications after TimeoutErrorWithResponse call are ignored.
TimeoutErrorWithResponse MUST be called before returning from RequestHandler if there are references to ctx and/or its members in other goroutines remain.
Usage of this function is discouraged. Prefer eliminating ctx references from pending goroutines instead of using this function.
func (*RequestCtx) URI ¶
func (ctx *RequestCtx) URI() *URI
URI returns requested uri.
This uri is valid until your request handler returns.
func (*RequestCtx) UserAgent ¶
func (ctx *RequestCtx) UserAgent() []byte
UserAgent returns User-Agent header value from the request.
The returned bytes are valid until your request handler returns.
func (*RequestCtx) UserValue ¶
func (ctx *RequestCtx) UserValue(key any) any
UserValue returns the value stored via SetUserValue* under the given key.
func (*RequestCtx) UserValueBytes ¶
func (ctx *RequestCtx) UserValueBytes(key []byte) any
UserValueBytes returns the value stored via SetUserValue* under the given key.
func (*RequestCtx) Value ¶
func (ctx *RequestCtx) Value(key any) any
Value returns the value associated with this context for key, or nil if no value is associated with key. Successive calls to Value with the same key returns the same result.
This method is present to make RequestCtx implement the context interface. This method is the same as calling ctx.UserValue(key).
func (*RequestCtx) VisitUserValues ¶
func (ctx *RequestCtx) VisitUserValues(visitor func([]byte, any))
VisitUserValues calls visitor for each existing userValue with a key that is a string or []byte.
visitor must not retain references to key and value after returning. Make key and/or value copies if you need storing them after returning.
func (*RequestCtx) VisitUserValuesAll ¶
func (ctx *RequestCtx) VisitUserValuesAll(visitor func(any, any))
VisitUserValuesAll calls visitor for each existing userValue.
visitor must not retain references to key and value after returning. Make key and/or value copies if you need storing them after returning.
func (*RequestCtx) Write ¶
func (ctx *RequestCtx) Write(p []byte) (int, error)
Write writes p into response body.
func (*RequestCtx) WriteString ¶
func (ctx *RequestCtx) WriteString(s string) (int, error)
WriteString appends s to response body.
type RequestHandler ¶
type RequestHandler func(*RequestCtx)
RequestHandler must process incoming requests.
RequestHandler must call ctx.TimeoutError() before returning if it keeps references to ctx and/or its members after the return. Consider wrapping RequestHandler into TimeoutHandler if response time must be limited.
func FSHandler ¶
func FSHandler(root string, stripSlashes int) RequestHandler
FSHandler returns request handler serving static files from the given root folder.
stripSlashes indicates how many leading slashes must be stripped from requested path before searching requested file in the root folder. Examples:
- stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar"
- stripSlashes = 1, original path: "/foo/bar", result: "/bar"
- stripSlashes = 2, original path: "/foo/bar", result: ""
The returned request handler automatically generates index pages for directories without index.html.
The returned handler caches requested file handles for FSHandlerCacheDuration. Make sure your program has enough 'max open files' limit aka 'ulimit -n' if root folder contains many files.
Do not create multiple request handler instances for the same (root, stripSlashes) arguments - just reuse a single instance. Otherwise goroutine leak will occur.
Example ¶
package main import ( "bytes" "log" "github.com/adhocore/fasthttp" ) // Setup file handlers (aka 'file server config'). var ( // Handler for serving images from /img/ path, // i.e. /img/foo/bar.jpg will be served from // /var/www/images/foo/bar.jpb . imgPrefix = []byte("/img/") imgHandler = fasthttp.FSHandler("/var/www/images", 1) // Handler for serving css from /static/css/ path, // i.e. /static/css/foo/bar.css will be served from // /home/dev/css/foo/bar.css . cssPrefix = []byte("/static/css/") cssHandler = fasthttp.FSHandler("/home/dev/css", 2) // Handler for serving the rest of requests, // i.e. /foo/bar/baz.html will be served from // /var/www/files/foo/bar/baz.html . filesHandler = fasthttp.FSHandler("/var/www/files", 0) ) // Main request handler. func requestHandler(ctx *fasthttp.RequestCtx) { path := ctx.Path() switch { case bytes.HasPrefix(path, imgPrefix): imgHandler(ctx) case bytes.HasPrefix(path, cssPrefix): cssHandler(ctx) default: filesHandler(ctx) } } func main() { if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil { log.Fatalf("Error in server: %v", err) } }
Output:
func TimeoutHandler ¶
func TimeoutHandler(h RequestHandler, timeout time.Duration, msg string) RequestHandler
TimeoutHandler creates RequestHandler, which returns StatusRequestTimeout error with the given msg to the client if h didn't return during the given duration.
The returned handler may return StatusTooManyRequests error with the given msg to the client if there are more than Server.Concurrency concurrent handlers h are running at the moment.
func TimeoutWithCodeHandler ¶
func TimeoutWithCodeHandler(h RequestHandler, timeout time.Duration, msg string, statusCode int) RequestHandler
TimeoutWithCodeHandler creates RequestHandler, which returns an error with the given msg and status code to the client if h didn't return during the given duration.
The returned handler may return StatusTooManyRequests error with the given msg to the client if there are more than Server.Concurrency concurrent handlers h are running at the moment.
type RequestHeader ¶
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, Cookie, Transfer-Encoding, Host and User-Agent headers can only be set once and will overwrite the previous value.
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 request 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) error
AddTrailerBytes add Trailer header value for chunked request 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) 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.
func (*RequestHeader) ContentType ¶
func (h *RequestHeader) ContentType() []byte
ContentType returns Content-Type header value.
func (*RequestHeader) Cookie ¶
func (h *RequestHeader) Cookie(key string) []byte
Cookie returns cookie for the given key.
func (*RequestHeader) CookieBytes ¶
func (h *RequestHeader) CookieBytes(key []byte) []byte
CookieBytes returns cookie for the given key.
func (*RequestHeader) CopyTo ¶
func (h *RequestHeader) CopyTo(dst *RequestHeader)
CopyTo copies all the headers to dst.
func (*RequestHeader) Del ¶
func (h *RequestHeader) Del(key string)
Del deletes header with the given key.
func (*RequestHeader) DelAllCookies ¶
func (h *RequestHeader) DelAllCookies()
DelAllCookies removes all the cookies from request headers.
func (*RequestHeader) DelBytes ¶
func (h *RequestHeader) DelBytes(key []byte)
DelBytes deletes header with the given key.
func (*RequestHeader) DelCookie ¶
func (h *RequestHeader) DelCookie(key string)
DelCookie removes cookie under the given key.
func (*RequestHeader) DelCookieBytes ¶
func (h *RequestHeader) DelCookieBytes(key []byte)
DelCookieBytes removes cookie under the given key.
func (*RequestHeader) DisableNormalizing ¶
func (h *RequestHeader) DisableNormalizing()
DisableNormalizing disables header names' normalization.
By default all the header names are normalized by uppercasing the first letter and all the first letters following dashes, while lowercasing all the other letters. Examples:
- CONNECTION -> Connection
- conteNT-tYPE -> Content-Type
- foo-bar-baz -> Foo-Bar-Baz
Disable header names' normalization only if know what are you doing.
func (*RequestHeader) 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) 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) IsConnect ¶
func (h *RequestHeader) IsConnect() bool
IsConnect returns true if request method is CONNECT.
func (*RequestHeader) IsDelete ¶
func (h *RequestHeader) IsDelete() bool
IsDelete returns true if request method is DELETE.
func (*RequestHeader) IsGet ¶
func (h *RequestHeader) IsGet() bool
IsGet returns true if request method is GET.
func (*RequestHeader) IsHTTP11 ¶
func (h *RequestHeader) IsHTTP11() bool
IsHTTP11 returns true if the request is HTTP/1.1.
func (*RequestHeader) IsHead ¶
func (h *RequestHeader) IsHead() bool
IsHead returns true if request method is HEAD.
func (*RequestHeader) IsOptions ¶
func (h *RequestHeader) IsOptions() bool
IsOptions returns true if request method is OPTIONS.
func (*RequestHeader) IsPatch ¶
func (h *RequestHeader) IsPatch() bool
IsPatch returns true if request method is PATCH.
func (*RequestHeader) IsPost ¶
func (h *RequestHeader) IsPost() bool
IsPost returns true if request method is POST.
func (*RequestHeader) IsPut ¶
func (h *RequestHeader) IsPut() bool
IsPut returns true if request method is PUT.
func (*RequestHeader) IsTrace ¶
func (h *RequestHeader) IsTrace() bool
IsTrace returns true if request method is TRACE.
func (*RequestHeader) Len ¶
func (h *RequestHeader) Len() int
Len returns the number of headers set, i.e. the number of times f is called in VisitAll.
func (*RequestHeader) Method ¶
func (h *RequestHeader) Method() []byte
Method returns HTTP request method.
func (*RequestHeader) MultipartFormBoundary ¶
func (h *RequestHeader) MultipartFormBoundary() []byte
MultipartFormBoundary returns boundary part from 'multipart/form-data; boundary=...' Content-Type.
func (*RequestHeader) Peek ¶
func (h *RequestHeader) Peek(key string) []byte
Peek returns header value for the given key.
The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead.
func (*RequestHeader) 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 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) 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 request 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) 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.
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.
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.
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.
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.
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) SetProtocol ¶
func (h *RequestHeader) SetProtocol(method string)
SetProtocol sets HTTP request protocol.
func (*RequestHeader) SetProtocolBytes ¶
func (h *RequestHeader) SetProtocolBytes(method []byte)
SetProtocolBytes sets HTTP request protocol.
func (*RequestHeader) SetReferer ¶
func (h *RequestHeader) SetReferer(referer string)
SetReferer sets Referer header value.
func (*RequestHeader) SetRefererBytes ¶
func (h *RequestHeader) SetRefererBytes(referer []byte)
SetRefererBytes sets Referer header value.
func (*RequestHeader) SetRequestURI ¶
func (h *RequestHeader) SetRequestURI(requestURI string)
SetRequestURI sets RequestURI for the first HTTP request line. RequestURI must be properly encoded. Use URI.RequestURI for constructing proper RequestURI if unsure.
func (*RequestHeader) SetRequestURIBytes ¶
func (h *RequestHeader) SetRequestURIBytes(requestURI []byte)
SetRequestURIBytes sets RequestURI for the first HTTP request line. RequestURI must be properly encoded. Use URI.RequestURI for constructing proper RequestURI if unsure.
func (*RequestHeader) SetTrailer ¶
func (h *RequestHeader) SetTrailer(trailer string) error
SetTrailer sets Trailer header value for chunked request 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 request 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) UserAgent ¶
func (h *RequestHeader) UserAgent() []byte
UserAgent returns User-Agent header value.
func (*RequestHeader) VisitAll ¶
func (h *RequestHeader) VisitAll(f func(key, value []byte))
VisitAll calls f for each header.
f must not retain references to key and/or value after returning. Copy key and/or value contents before returning if you need retaining them.
To get the headers in order they were received use VisitAllInOrder.
func (*RequestHeader) VisitAllCookie ¶
func (h *RequestHeader) VisitAllCookie(f func(key, value []byte))
VisitAllCookie calls f for each request cookie.
f must not retain references to key and/or value after returning.
func (*RequestHeader) VisitAllInOrder ¶
func (h *RequestHeader) VisitAllInOrder(f func(key, value []byte))
VisitAllInOrder calls f for each header in the order they were received.
f must not retain references to key and/or value after returning. Copy key and/or value contents before returning if you need retaining them.
This function is slightly slower than VisitAll because it has to reparse the raw headers to get the order.
func (*RequestHeader) VisitAllTrailer ¶
func (h *RequestHeader) VisitAllTrailer(f func(value []byte))
VisitAllTrailer calls f for each request Trailer.
f must not retain references to value after returning.
type Response ¶
type Response struct { // Response header. // // Copying Header by value is forbidden. Use pointer to Header instead. Header ResponseHeader // Flush headers as soon as possible without waiting for first body bytes. // Relevant for bodyStream only. ImmediateHeaderFlush bool // StreamBody enables response body streaming. // Use SetBodyStream to set the body stream. StreamBody bool // Response.Read() skips reading body if set to true. // Use it for reading HEAD responses. // // Response.Write() skips writing body if set to true. // Use it for writing HEAD responses. SkipBody bool // contains filtered or unexported fields }
Response represents HTTP response.
It is forbidden copying Response instances. Create new instances and use CopyTo instead.
Response instance MUST NOT be used from concurrently running goroutines.
func AcquireResponse ¶
func AcquireResponse() *Response
AcquireResponse returns an empty Response instance from response pool.
The returned Response instance may be passed to ReleaseResponse when it is no longer needed. This allows Response recycling, reduces GC pressure and usually improves performance.
func (*Response) AppendBody ¶
AppendBody appends p to response body.
It is safe re-using p after the function returns.
func (*Response) AppendBodyString ¶
AppendBodyString appends s to response body.
func (*Response) Body ¶
Body returns response body.
The returned value is valid until the response is released, either though ReleaseResponse or your request handler returning. Do not store references to returned value. Make copies instead.
func (*Response) BodyGunzip ¶
BodyGunzip returns un-gzipped body data.
This method may be used if the response header contains 'Content-Encoding: gzip' for reading un-gzipped body. Use Body for reading gzipped response body.
func (*Response) BodyInflate ¶
BodyInflate returns inflated body data.
This method may be used if the response header contains 'Content-Encoding: deflate' for reading inflated response body. Use Body for reading deflated response body.
func (*Response) BodyStream ¶
BodyStream returns io.Reader.
You must CloseBodyStream or ReleaseResponse after you use it.
func (*Response) BodyUncompressed ¶
BodyUncompressed returns body data and if needed decompress it from gzip, deflate or Brotli.
This method may be used if the response header contains 'Content-Encoding' for reading uncompressed response body. Use Body for reading the raw response body.
func (*Response) BodyWriteTo ¶
BodyWriteTo writes response body to w.
func (*Response) BodyWriter ¶
BodyWriter returns writer for populating response body.
If used inside RequestHandler, the returned writer must not be used after returning from RequestHandler. Use RequestCtx.Write or SetBodyStreamWriter in this case.
func (*Response) CloseBodyStream ¶
func (*Response) ConnectionClose ¶
ConnectionClose returns true if 'Connection: close' header is set.
func (*Response) IsBodyStream ¶
IsBodyStream returns true if body is set via SetBodyStream*.
func (*Response) LocalAddr ¶
LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
func (*Response) Read ¶
Read reads response (including body) from the given r.
io.EOF is returned if r is closed before reading the first header byte.
func (*Response) ReadBody ¶
ReadBody reads response body from the given r, limiting the body size.
If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned.
func (*Response) ReadLimitBody ¶
ReadLimitBody reads response headers from the given r, then reads the body using the ReadBody function and limiting the body size.
If resp.SkipBody is true then it skips reading the response body.
If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned.
io.EOF is returned if r is closed before reading the first header byte.
func (*Response) ReleaseBody ¶
ReleaseBody retires the response body if it is greater than "size" bytes.
This permits GC to reclaim the large buffer. If used, must be before ReleaseResponse.
Use this method only if you really understand how it works. The majority of workloads don't need this method.
func (*Response) RemoteAddr ¶
RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
func (*Response) SendFile ¶
SendFile registers file on the given path to be used as response body when Write is called.
Note that SendFile doesn't set Content-Type, so set it yourself with Header.SetContentType.
func (*Response) SetBody ¶
SetBody sets response body.
It is safe re-using body argument after the function returns.
func (*Response) SetBodyRaw ¶
SetBodyRaw sets response body, but without copying it.
From this point onward the body argument must not be changed.
func (*Response) SetBodyStream ¶
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) SetBodyString ¶
SetBodyString sets response body.
func (*Response) SetConnectionClose ¶
func (resp *Response) SetConnectionClose()
SetConnectionClose sets 'Connection: close' header.
func (*Response) SetStatusCode ¶
SetStatusCode sets response status code.
func (*Response) StatusCode ¶
StatusCode returns response status code.
func (*Response) String ¶
String returns response representation.
Returns error message instead of response representation on error.
Use Write instead of String for performance-critical code.
func (*Response) SwapBody ¶
SwapBody swaps response body with the given body and returns the previous response body.
It is forbidden to use the body passed to SwapBody after the function returns.
func (*Response) Write ¶
Write writes response to w.
Write doesn't flush response to w for performance reasons.
See also WriteTo.
func (*Response) WriteDeflate ¶
WriteDeflate writes response with deflated body to w.
The method deflates response body and sets 'Content-Encoding: deflate' header before writing response to w.
WriteDeflate doesn't flush response to w for performance reasons.
func (*Response) WriteDeflateLevel ¶
WriteDeflateLevel writes response with deflated body to w.
Level is the desired compression level:
- CompressNoCompression
- CompressBestSpeed
- CompressBestCompression
- CompressDefaultCompression
- CompressHuffmanOnly
The method deflates response body and sets 'Content-Encoding: deflate' header before writing response to w.
WriteDeflateLevel doesn't flush response to w for performance reasons.
func (*Response) WriteGzip ¶
WriteGzip writes response with gzipped body to w.
The method gzips response body and sets 'Content-Encoding: gzip' header before writing response to w.
WriteGzip doesn't flush response to w for performance reasons.
func (*Response) WriteGzipLevel ¶
WriteGzipLevel writes response with gzipped body to w.
Level is the desired compression level:
- CompressNoCompression
- CompressBestSpeed
- CompressBestCompression
- CompressDefaultCompression
- CompressHuffmanOnly
The method gzips response body and sets 'Content-Encoding: gzip' header before writing response to w.
WriteGzipLevel doesn't flush response to w for performance reasons.
type ResponseHeader ¶
type ResponseHeader struct {
// contains filtered or unexported fields
}
ResponseHeader represents HTTP response header.
It is forbidden copying ResponseHeader instances. Create new instances instead and use CopyTo.
ResponseHeader instance MUST NOT be used from concurrently running goroutines.
func (*ResponseHeader) Add ¶
func (h *ResponseHeader) Add(key, value string)
Add adds the given 'key: value' header.
Multiple headers with the same key may be added with this function. Use Set for setting a single header for the given key.
the Content-Type, Content-Length, Connection, Server, Set-Cookie, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value.
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, Set-Cookie, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value.
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, Set-Cookie, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value.
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, Set-Cookie, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value.
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) 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) 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) 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 response is HTTP/1.1.
func (*ResponseHeader) Len ¶
func (h *ResponseHeader) Len() int
Len returns the number of headers set, i.e. the number of times f is called in VisitAll.
func (*ResponseHeader) Peek ¶
func (h *ResponseHeader) Peek(key string) []byte
Peek returns header value for the given key.
The returned value is valid until the response is released, either though ReleaseResponse or your request handler returning. Do not store references to the returned value. Make copies instead.
func (*ResponseHeader) PeekAll ¶
func (h *ResponseHeader