fasthttp

package module
v0.0.0-...-9759ddc Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2024 License: MIT Imports: 55 Imported by: 0

README

fasthttp GoDoc Go Report

Fast HTTP implementation for Go.

fasthttp might not be for you!

fasthttp was designed for some high performance edge cases. Unless your server/client needs to handle thousands of small to medium requests per second and needs a consistent low millisecond response time fasthttp might not be for you. For most cases net/http is much better as it's easier to use and can handle more cases. For most cases you won't even notice the performance difference.

Currently fasthttp is successfully used by VertaMedia in a production serving up to 200K rps from more than 1.5M concurrent keep-alive connections per physical server.

TechEmpower Benchmark round 19 results

Server Benchmarks

Client Benchmarks

Install

Documentation

Examples from docs

Code examples

Awesome fasthttp tools

Switching from net/http to fasthttp

Fasthttp best practices

Tricks with byte buffers

Related projects

FAQ

HTTP server performance comparison with net/http

In short, fasthttp server is up to 10 times faster than net/http. Below are benchmark results.

GOMAXPROCS=1

net/http server:

$ GOMAXPROCS=1 go test -bench=NetHTTPServerGet -benchmem -benchtime=10s
BenchmarkNetHTTPServerGet1ReqPerConn                	 1000000	     12052 ns/op	    2297 B/op	      29 allocs/op
BenchmarkNetHTTPServerGet2ReqPerConn                	 1000000	     12278 ns/op	    2327 B/op	      24 allocs/op
BenchmarkNetHTTPServerGet10ReqPerConn               	 2000000	      8903 ns/op	    2112 B/op	      19 allocs/op
BenchmarkNetHTTPServerGet10KReqPerConn              	 2000000	      8451 ns/op	    2058 B/op	      18 allocs/op
BenchmarkNetHTTPServerGet1ReqPerConn10KClients      	  500000	     26733 ns/op	    3229 B/op	      29 allocs/op
BenchmarkNetHTTPServerGet2ReqPerConn10KClients      	 1000000	     23351 ns/op	    3211 B/op	      24 allocs/op
BenchmarkNetHTTPServerGet10ReqPerConn10KClients     	 1000000	     13390 ns/op	    2483 B/op	      19 allocs/op
BenchmarkNetHTTPServerGet100ReqPerConn10KClients    	 1000000	     13484 ns/op	    2171 B/op	      18 allocs/op

fasthttp server:

$ GOMAXPROCS=1 go test -bench=kServerGet -benchmem -benchtime=10s
BenchmarkServerGet1ReqPerConn                       	10000000	      1559 ns/op	       0 B/op	       0 allocs/op
BenchmarkServerGet2ReqPerConn                       	10000000	      1248 ns/op	       0 B/op	       0 allocs/op
BenchmarkServerGet10ReqPerConn                      	20000000	       797 ns/op	       0 B/op	       0 allocs/op
BenchmarkServerGet10KReqPerConn                     	20000000	       716 ns/op	       0 B/op	       0 allocs/op
BenchmarkServerGet1ReqPerConn10KClients             	10000000	      1974 ns/op	       0 B/op	       0 allocs/op
BenchmarkServerGet2ReqPerConn10KClients             	10000000	      1352 ns/op	       0 B/op	       0 allocs/op
BenchmarkServerGet10ReqPerConn10KClients            	20000000	       789 ns/op	       2 B/op	       0 allocs/op
BenchmarkServerGet100ReqPerConn10KClients           	20000000	       604 ns/op	       0 B/op	       0 allocs/op

GOMAXPROCS=4

net/http server:

$ GOMAXPROCS=4 go test -bench=NetHTTPServerGet -benchmem -benchtime=10s
BenchmarkNetHTTPServerGet1ReqPerConn-4                  	 3000000	      4529 ns/op	    2389 B/op	      29 allocs/op
BenchmarkNetHTTPServerGet2ReqPerConn-4                  	 5000000	      3896 ns/op	    2418 B/op	      24 allocs/op
BenchmarkNetHTTPServerGet10ReqPerConn-4                 	 5000000	      3145 ns/op	    2160 B/op	      19 allocs/op
BenchmarkNetHTTPServerGet10KReqPerConn-4                	 5000000	      3054 ns/op	    2065 B/op	      18 allocs/op
BenchmarkNetHTTPServerGet1ReqPerConn10KClients-4        	 1000000	     10321 ns/op	    3710 B/op	      30 allocs/op
BenchmarkNetHTTPServerGet2ReqPerConn10KClients-4        	 2000000	      7556 ns/op	    3296 B/op	      24 allocs/op
BenchmarkNetHTTPServerGet10ReqPerConn10KClients-4       	 5000000	      3905 ns/op	    2349 B/op	      19 allocs/op
BenchmarkNetHTTPServerGet100ReqPerConn10KClients-4      	 5000000	      3435 ns/op	    2130 B/op	      18 allocs/op

fasthttp server:

$ GOMAXPROCS=4 go test -bench=kServerGet -benchmem -benchtime=10s
BenchmarkServerGet1ReqPerConn-4                         	10000000	      1141 ns/op	       0 B/op	       0 allocs/op
BenchmarkServerGet2ReqPerConn-4                         	20000000	       707 ns/op	       0 B/op	       0 allocs/op
BenchmarkServerGet10ReqPerConn-4                        	30000000	       341 ns/op	       0 B/op	       0 allocs/op
BenchmarkServerGet10KReqPerConn-4                       	50000000	       310 ns/op	       0 B/op	       0 allocs/op
BenchmarkServerGet1ReqPerConn10KClients-4               	10000000	      1119 ns/op	       0 B/op	       0 allocs/op
BenchmarkServerGet2ReqPerConn10KClients-4               	20000000	       644 ns/op	       0 B/op	       0 allocs/op
BenchmarkServerGet10ReqPerConn10KClients-4              	30000000	       346 ns/op	       0 B/op	       0 allocs/op
BenchmarkServerGet100ReqPerConn10KClients-4             	50000000	       282 ns/op	       0 B/op	       0 allocs/op

HTTP client comparison with net/http

In short, fasthttp client is up to 10 times faster than net/http. Below are benchmark results.

GOMAXPROCS=1

net/http client:

$ GOMAXPROCS=1 go test -bench='HTTPClient(Do|GetEndToEnd)' -benchmem -benchtime=10s
BenchmarkNetHTTPClientDoFastServer                  	 1000000	     12567 ns/op	    2616 B/op	      35 allocs/op
BenchmarkNetHTTPClientGetEndToEnd1TCP               	  200000	     67030 ns/op	    5028 B/op	      56 allocs/op
BenchmarkNetHTTPClientGetEndToEnd10TCP              	  300000	     51098 ns/op	    5031 B/op	      56 allocs/op
BenchmarkNetHTTPClientGetEndToEnd100TCP             	  300000	     45096 ns/op	    5026 B/op	      55 allocs/op
BenchmarkNetHTTPClientGetEndToEnd1Inmemory          	  500000	     24779 ns/op	    5035 B/op	      57 allocs/op
BenchmarkNetHTTPClientGetEndToEnd10Inmemory         	 1000000	     26425 ns/op	    5035 B/op	      57 allocs/op
BenchmarkNetHTTPClientGetEndToEnd100Inmemory        	  500000	     28515 ns/op	    5045 B/op	      57 allocs/op
BenchmarkNetHTTPClientGetEndToEnd1000Inmemory       	  500000	     39511 ns/op	    5096 B/op	      56 allocs/op

fasthttp client:

$ GOMAXPROCS=1 go test -bench='kClient(Do|GetEndToEnd)' -benchmem -benchtime=10s
BenchmarkClientDoFastServer                         	20000000	       865 ns/op	       0 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd1TCP                      	 1000000	     18711 ns/op	       0 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd10TCP                     	 1000000	     14664 ns/op	       0 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd100TCP                    	 1000000	     14043 ns/op	       1 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd1Inmemory                 	 5000000	      3965 ns/op	       0 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd10Inmemory                	 3000000	      4060 ns/op	       0 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd100Inmemory               	 5000000	      3396 ns/op	       0 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd1000Inmemory              	 5000000	      3306 ns/op	       2 B/op	       0 allocs/op

GOMAXPROCS=4

net/http client:

$ GOMAXPROCS=4 go test -bench='HTTPClient(Do|GetEndToEnd)' -benchmem -benchtime=10s
BenchmarkNetHTTPClientDoFastServer-4                    	 2000000	      8774 ns/op	    2619 B/op	      35 allocs/op
BenchmarkNetHTTPClientGetEndToEnd1TCP-4                 	  500000	     22951 ns/op	    5047 B/op	      56 allocs/op
BenchmarkNetHTTPClientGetEndToEnd10TCP-4                	 1000000	     19182 ns/op	    5037 B/op	      55 allocs/op
BenchmarkNetHTTPClientGetEndToEnd100TCP-4               	 1000000	     16535 ns/op	    5031 B/op	      55 allocs/op
BenchmarkNetHTTPClientGetEndToEnd1Inmemory-4            	 1000000	     14495 ns/op	    5038 B/op	      56 allocs/op
BenchmarkNetHTTPClientGetEndToEnd10Inmemory-4           	 1000000	     10237 ns/op	    5034 B/op	      56 allocs/op
BenchmarkNetHTTPClientGetEndToEnd100Inmemory-4          	 1000000	     10125 ns/op	    5045 B/op	      56 allocs/op
BenchmarkNetHTTPClientGetEndToEnd1000Inmemory-4         	 1000000	     11132 ns/op	    5136 B/op	      56 allocs/op

fasthttp client:

$ GOMAXPROCS=4 go test -bench='kClient(Do|GetEndToEnd)' -benchmem -benchtime=10s
BenchmarkClientDoFastServer-4                           	50000000	       397 ns/op	       0 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd1TCP-4                        	 2000000	      7388 ns/op	       0 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd10TCP-4                       	 2000000	      6689 ns/op	       0 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd100TCP-4                      	 3000000	      4927 ns/op	       1 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd1Inmemory-4                   	10000000	      1604 ns/op	       0 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd10Inmemory-4                  	10000000	      1458 ns/op	       0 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd100Inmemory-4                 	10000000	      1329 ns/op	       0 B/op	       0 allocs/op
BenchmarkClientGetEndToEnd1000Inmemory-4                	10000000	      1316 ns/op	       5 B/op	       0 allocs/op

Install

go get -u github.com/valyala/fasthttp

Switching from net/http to fasthttp

Unfortunately, fasthttp doesn't provide API identical to net/http. See the FAQ for details. There is net/http -> fasthttp handler converter, but it is better to write fasthttp request handlers by hand in order to use all of the fasthttp advantages (especially high performance :) ).

Important points:

  • Fasthttp works with RequestHandler functions instead of objects implementing Handler interface. Fortunately, it is easy to pass bound struct methods to fasthttp:

    type MyHandler struct {
    	foobar string
    }
    
    // request handler in net/http style, i.e. method bound to MyHandler struct.
    func (h *MyHandler) HandleFastHTTP(ctx *fasthttp.RequestCtx) {
    	// notice that we may access MyHandler properties here - see h.foobar.
    	fmt.Fprintf(ctx, "Hello, world! Requested path is %q. Foobar is %q",
    		ctx.Path(), h.foobar)
    }
    
    // request handler in fasthttp style, i.e. just plain function.
    func fastHTTPHandler(ctx *fasthttp.RequestCtx) {
    	fmt.Fprintf(ctx, "Hi there! RequestURI is %q", ctx.RequestURI())
    }
    
    // pass bound struct method to fasthttp
    myHandler := &MyHandler{
    	foobar: "foobar",
    }
    fasthttp.ListenAndServe(":8080", myHandler.HandleFastHTTP)
    
    // pass plain function to fasthttp
    fasthttp.ListenAndServe(":8081", fastHTTPHandler)
    
  • The RequestHandler accepts only one argument - RequestCtx. It contains all the functionality required for http request processing and response writing. Below is an example of a simple request handler conversion from net/http to fasthttp.

    // net/http request handler
    requestHandler := func(w http.ResponseWriter, r *http.Request) {
    	switch r.URL.Path {
    	case "/foo":
    		fooHandler(w, r)
    	case "/bar":
    		barHandler(w, r)
    	default:
    		http.Error(w, "Unsupported path", http.StatusNotFound)
    	}
    }
    
    // the corresponding fasthttp request handler
    requestHandler := func(ctx *fasthttp.RequestCtx) {
    	switch string(ctx.Path()) {
    	case "/foo":
    		fooHandler(ctx)
    	case "/bar":
    		barHandler(ctx)
    	default:
    		ctx.Error("Unsupported path", fasthttp.StatusNotFound)
    	}
    }
    
  • Fasthttp allows setting response headers and writing response body in an arbitrary order. There is no 'headers first, then body' restriction like in net/http. The following code is valid for fasthttp:

    requestHandler := func(ctx *fasthttp.RequestCtx) {
    	// set some headers and status code first
    	ctx.SetContentType("foo/bar")
    	ctx.SetStatusCode(fasthttp.StatusOK)
    
    	// then write the first part of body
    	fmt.Fprintf(ctx, "this is the first part of body\n")
    
    	// then set more headers
    	ctx.Response.Header.Set("Foo-Bar", "baz")
    
    	// then write more body
    	fmt.Fprintf(ctx, "this is the second part of body\n")
    
    	// then override already written body
    	ctx.SetBody([]byte("this is completely new body contents"))
    
    	// then update status code
    	ctx.SetStatusCode(fasthttp.StatusNotFound)
    
    	// basically, anything may be updated many times before
    	// returning from RequestHandler.
    	//
    	// Unlike net/http fasthttp doesn't put response to the wire until
    	// returning from RequestHandler.
    }
    
  • Fasthttp doesn't provide ServeMux, but there are more powerful third-party routers and web frameworks with fasthttp support:

    Net/http code with simple ServeMux is trivially converted to fasthttp code:

    // net/http code
    
    m := &http.ServeMux{}
    m.HandleFunc("/foo", fooHandlerFunc)
    m.HandleFunc("/bar", barHandlerFunc)
    m.Handle("/baz", bazHandler)
    
    http.ListenAndServe(":80", m)
    
    // the corresponding fasthttp code
    m := func(ctx *fasthttp.RequestCtx) {
    	switch string(ctx.Path()) {
    	case "/foo":
    		fooHandlerFunc(ctx)
    	case "/bar":
    		barHandlerFunc(ctx)
    	case "/baz":
    		bazHandler.HandlerFunc(ctx)
    	default:
    		ctx.Error("not found", fasthttp.StatusNotFound)
    	}
    }
    
    fasthttp.ListenAndServe(":80", m)
    
  • Because creating a new channel for every request is just too expensive, so the channel returned by RequestCtx.Done() is only closed when the server is shutting down.

    func main() {
      fasthttp.ListenAndServe(":8080", fasthttp.TimeoutHandler(func(ctx *fasthttp.RequestCtx) {
      	select {
      	case <-ctx.Done():
      		// ctx.Done() is only closed when the server is shutting down.
      		log.Println("context cancelled")
      		return
      	case <-time.After(10 * time.Second):
      		log.Println("process finished ok")
      	}
      }, time.Second*2, "timeout"))
    }
    
  • net/http -> fasthttp conversion table:

    • All the pseudocode below assumes w, r and ctx have these types:
      var (
      	w http.ResponseWriter
      	r *http.Request
      	ctx *fasthttp.RequestCtx
      )
    
  • VERY IMPORTANT! Fasthttp disallows holding references to RequestCtx or to its' members after returning from RequestHandler. Otherwise data races are inevitable. Carefully inspect all the net/http request handlers converted to fasthttp whether they retain references to RequestCtx or to its' members after returning. RequestCtx provides the following band aids for this case:

    • Wrap RequestHandler into TimeoutHandler.
    • Call TimeoutError before returning from RequestHandler if there are references to RequestCtx or to its' members. See the example for more details.

Use this brilliant tool - race detector - for detecting and eliminating data races in your program. If you detected data race related to fasthttp in your program, then there is high probability you forgot calling TimeoutError before returning from RequestHandler.

Performance optimization tips for multi-core systems

  • Use reuseport listener.
  • Run a separate server instance per CPU core with GOMAXPROCS=1.
  • Pin each server instance to a separate CPU core using taskset.
  • Ensure the interrupts of multiqueue network card are evenly distributed between CPU cores. See this article for details.
  • Use the latest version of Go as each version contains performance improvements.

Fasthttp best practices

  • Do not allocate objects and []byte buffers - just reuse them as much as possible. Fasthttp API design encourages this.
  • sync.Pool is your best friend.
  • Profile your program in production. go tool pprof --alloc_objects your-program mem.pprof usually gives better insights for optimization opportunities than go tool pprof your-program cpu.pprof.
  • Write tests and benchmarks for hot paths.
  • Avoid conversion between []byte and string, since this may result in memory allocation+copy. Fasthttp API provides functions for both []byte and string - use these functions instead of converting manually between []byte and string. There are some exceptions - see this wiki page for more details.
  • Verify your tests and production code under race detector on a regular basis.
  • Prefer quicktemplate instead of html/template in your webserver.

Tricks with []byte buffers

The following tricks are used by fasthttp. Use them in your code too.

  • Standard Go functions accept nil buffers
var (
	// both buffers are uninitialized
	dst []byte
	src []byte
)
dst = append(dst, src...)  // is legal if dst is nil and/or src is nil
copy(dst, src)  // is legal if dst is nil and/or src is nil
(string(src) == "")  // is true if src is nil
(len(src) == 0)  // is true if src is nil
src = src[:0]  // works like a charm with nil src

// this for loop doesn't panic if src is nil
for i, ch := range src {
	doSomething(i, ch)
}

So throw away nil checks for []byte buffers from you code. For example,

srcLen := 0
if src != nil {
	srcLen = len(src)
}

becomes

srcLen := len(src)
  • String may be appended to []byte buffer with append
dst = append(dst, "foobar"...)
  • []byte buffer may be extended to its' capacity.
buf := make([]byte, 100)
a := buf[:10]  // len(a) == 10, cap(a) == 100.
b := a[:100]  // is valid, since cap(a) == 100.
  • All fasthttp functions accept nil []byte buffer
statusCode, body, err := fasthttp.Get(nil, "http://google.com/")
uintBuf := fasthttp.AppendUint(nil, 1234)
  • String and []byte buffers may converted without memory allocations
func b2s(b []byte) string {
    return *(*string)(unsafe.Pointer(&b))
}

func s2b(s string) (b []byte) {
    bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
    sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
    bh.Data = sh.Data
    bh.Cap = sh.Len
    bh.Len = sh.Len
    return b
}
Warning:

This is an unsafe way, the result string and []byte buffer share the same bytes.

Please make sure not to modify the bytes in the []byte buffer if the string still survives!

  • fasthttp - various useful helpers for projects based on fasthttp.
  • fasthttp-routing - fast and powerful routing package for fasthttp servers.
  • http2 - HTTP/2 implementation for fasthttp.
  • router - a high performance fasthttp request router that scales well.
  • fastws - Bloatless WebSocket package made for fasthttp to handle Read/Write operations concurrently.
  • gramework - a web framework made by one of fasthttp maintainers
  • lu - a high performance go middleware web framework which is based on fasthttp.
  • websocket - Gorilla-based websocket implementation for fasthttp.
  • websocket - Event-based high-performance WebSocket library for zero-allocation websocket servers and clients.
  • fasthttpsession - a fast and powerful session package for fasthttp servers.
  • atreugo - High performance and extensible micro web framework with zero memory allocations in hot paths.
  • kratgo - Simple, lightweight and ultra-fast HTTP Cache to speed up your websites.
  • kit-plugins - go-kit transport implementation for fasthttp.
  • Fiber - An Expressjs inspired web framework running on Fasthttp
  • Gearbox - ⚙ gearbox is a web framework written in Go with a focus on high performance and memory optimization
  • http2curl - A tool to convert fasthttp requests to curl command line

FAQ

  • Why creating yet another http package instead of optimizing net/http?

    Because net/http API limits many optimization opportunities. For example:

    • net/http Request object lifetime isn't limited by request handler execution time. So the server must create a new request object per each request instead of reusing existing objects like fasthttp does.
    • net/http headers are stored in a map[string][]string. So the server must parse all the headers, convert them from []byte to string and put them into the map before calling user-provided request handler. This all requires unnecessary memory allocations avoided by fasthttp.
    • net/http client API requires creating a new response object per each request.
  • Why fasthttp API is incompatible with net/http?

    Because net/http API limits many optimization opportunities. See the answer above for more details. Also certain net/http API parts are suboptimal for use:

  • Why fasthttp doesn't support HTTP/2.0 and WebSockets?

    HTTP/2.0 support is in progress. WebSockets has been done already. Third parties also may use RequestCtx.Hijack for implementing these goodies.

  • Are there known net/http advantages comparing to fasthttp?

    Yes:

    • net/http supports HTTP/2.0 starting from go1.6.
    • net/http API is stable, while fasthttp API constantly evolves.
    • net/http handles more HTTP corner cases.
    • net/http can stream both request and response bodies
    • net/http can handle bigger bodies as it doesn't read the whole body into memory
    • net/http should contain less bugs, since it is used and tested by much wider audience.
  • Why fasthttp API prefers returning []byte instead of string?

    Because []byte to string conversion isn't free - it requires memory allocation and copy. Feel free wrapping returned []byte result into string() if you prefer working with strings instead of byte slices. But be aware that this has non-zero overhead.

  • Which GO versions are supported by fasthttp?

    Go 1.18.x. Older versions won't be supported.

  • Please provide real benchmark data and server information

    See this issue.

  • Are there plans to add request routing to fasthttp?

    There are no plans to add request routing into fasthttp. Use third-party routers and web frameworks with fasthttp support:

    See also this issue for more info.

  • I detected data race in fasthttp!

    Cool! File a bug. But before doing this check the following in your code:

  • I didn't find an answer for my question here

    Try exploring these questions.

Documentation

Overview

Package fasthttp provides fast HTTP server and client API.

Fasthttp provides the following features:

  1. Optimized for speed. Easily handles more than 100K qps and more than 1M concurrent keep-alive connections on modern hardware.

  2. Optimized for low memory usage.

  3. Easy 'Connection: Upgrade' support via RequestCtx.Hijack.

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

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

  6. Client supports automatic retry on idempotent requests' failure.

  7. Fasthttp API is designed with the ability to extend existing client and server implementations or to write custom client and server implementations from scratch.

Index

Examples

Constants

View Source
const (
	CompressBrotliNoCompression      = 0
	CompressBrotliBestSpeed          = brotli.BestSpeed
	CompressBrotliBestCompression    = brotli.BestCompression
	CompressBrotliDefaultCompression = 3
)

Supported compression levels.

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

Supported compression levels.

View Source
const (
	HTTPSchemePrefix  = "http://"
	HTTPSSchemePrefix = "https://"
)
View Source
const (
	HeaderAuthorization      = "Authorization"
	HeaderProxyAuthenticate  = "Proxy-Authenticate"
	HeaderProxyAuthorization = "Proxy-Authorization"
	HeaderWWWAuthenticate    = "WWW-Authenticate"

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

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

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

	HeaderConnection      = "Connection"
	HeaderKeepAlive       = "Keep-Alive"
	HeaderProxyConnection = "Proxy-Connection"

	HeaderAccept         = "Accept"
	HeaderAcceptCharset  = "Accept-Charset"
	HeaderAcceptEncoding = "Accept-Encoding"
	HeaderAcceptLanguage = "Accept-Language"

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

	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"

	HeaderDNT = "DNT"
	HeaderTk  = "Tk"

	HeaderContentDisposition = "Content-Disposition"

	HeaderContentEncoding = "Content-Encoding"
	HeaderContentLanguage = "Content-Language"
	HeaderContentLength   = "Content-Length"
	HeaderContentLocation = "Content-Location"
	HeaderContentType     = "Content-Type"

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

	HeaderLocation = "Location"

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

	HeaderAllow  = "Allow"
	HeaderServer = "Server"

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

	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"

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

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

	HeaderSecWebSocketAccept     = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions" /* #nosec G101 */
	HeaderSecWebSocketKey        = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol   = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion    = "Sec-WebSocket-Version"

	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"

	CharsetUTF8 = "UTF-8"
	CharsetGBK  = "GBK"
)

Headers.

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

HTTP methods were copied from net/http.

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

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

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

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

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest           = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes were stolen from net/http.

View Source
const (
	TCP4 = "tcp4"
	TCP  = "tcp"
)
View Source
const (
	CompressZstdSpeedNotSet = iota
	CompressZstdBestSpeed
	CompressZstdDefault
	CompressZstdSpeedBetter
	CompressZstdBestCompression
)
View Source
const BinaryInplaceThreshold = block4k

BinaryInplaceThreshold marks the minimum value of the nocopy slice length, which is the threshold to use copy to minimize overhead.

View Source
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).

View Source
const DefaultDNSCacheDuration = time.Minute

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

View Source
const DefaultDialTimeout = 3 * time.Second

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

View Source
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.

View Source
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).

View Source
const DefaultMaxIdemponentCallAttempts = 5

DefaultMaxIdemponentCallAttempts is the default idempotent calls attempts count.

View Source
const DefaultMaxIdleConnDuration = 10 * time.Second

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

View Source
const DefaultMaxPendingRequests = 1024

DefaultMaxPendingRequests is the default value for PipelineClient.MaxPendingRequests.

View Source
const DefaultMaxRequestBodySize = 4 * 1024 * 1024

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

See Server.MaxRequestBodySize for details.

View Source
const FSHandlerCacheDuration = 60 * time.Second

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

Variables

View Source
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")

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

	// ErrHostClientRedirectToDifferentHost HostClients are only able to follow redirects to the same host.
	ErrHostClientRedirectToDifferentHost = errors.New("HostClient can't follow redirects to a different host," +
		" please use Client instead")
)
View Source
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")
)
View Source
var (
	// CookieExpireDelete may be set on Cookie.Expire for expiring the given cookie.
	CookieExpireDelete = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)

	// CookieExpireUnlimited indicates that the cookie doesn't expire.
	CookieExpireUnlimited = zeroTime
)
View Source
var (
	// 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")
)
View Source
var BadTrailerInHeader = newHeaderParseErr("header contain forbidden trailer", "")
View Source
var CompressFuncs = [5]func(response *Response, level int){
	(*Response).gzipBody, (*Response).gzipBody, (*Response).brotliBody, (*Response).deflateBody, (*Response).zstdBody,
}
View Source
var ContentLengthNotIntErr = newHeaderParseErr("Content-Length not int string", "")
View Source
var DefaultBigFileReaderCount = 400
View Source
var DefaultCleanThresholdFunc = func(t1, t2, t3, t4 *time.Time, readyLen, maxWorkersCount int, maxIdleWorkerDuration time.Duration) (cleanNum int) {
	if readyLen <= 2>>10 {
		return
	}

	now := time.Now()
	if readyLen <= maxWorkersCount>>2 {
		if now.Sub(*t3) > maxIdleWorkerDuration {
			return readyLen >> 2
		}
		if now.Sub(*t4) > maxIdleWorkerDuration {
			return readyLen >> 1
		}
		return
	}

	if readyLen <= maxWorkersCount>>1 {
		if now.Sub(*t2) > maxIdleWorkerDuration {
			return readyLen >> 2
		}
		if now.Sub(*t3) > maxIdleWorkerDuration {
			return readyLen >> 1
		}
		return
	}

	if readyLen <= maxWorkersCount {
		if now.Sub(*t3) > maxIdleWorkerDuration {
			return readyLen >> 1
		}
		return
	}

	return 0
}
View Source
var DefaultCompressedFileSuffixes = [3]string{
	".fasthttp.br", ".fasthttp.gz", ".fasthttp.zst",
}

DefaultCompressedFileSuffixes 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 DefaultCompressedFileSuffixes = map[string]string{
	"gzip": ".fasthttp.gz",
	"br":   ".fasthttp.br",
	"zstd": ".fasthttp.zst",
}

DefaultCompressedFileSuffixes cache kind2suffix

View Source
var EmptyHeaderKeyErr = newHeaderParseErr("empty header key", "")
View Source
var ErrBadTrailer = errors.New("contain forbidden trailer")
View Source
var ErrBodyTooLarge = errors.New("body size exceeds the given limit")

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

View Source
var ErrCertAndKeyMustProvided = errors.New("cert and key must be both provided")
View Source
var ErrContentEncodingUnsupported = errors.New("unsupported Content-Encoding")
View Source
var ErrDialTimeout = errors.New("dialing to the given TCP address timed out")

ErrDialTimeout is returned when TCP dialing is timed out.

View Source
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).

View Source
var ErrMalformedResponse = fmt.Errorf("malformed HTTP response")

ErrMalformedResponse is returned by Dialer to indicate that server response can not be parsed.

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

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

View Source
var 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.

View Source
var ErrTLSHandshakeTimeout = errors.New("tls handshake timed out")

ErrTLSHandshakeTimeout indicates there is a timeout from tls handshake.

View Source
var ErrTimeout = &timeoutError{}

ErrTimeout is returned from timed out calls.

View Source
var ErrUnSupportConnPoolStrategy = errors.New("unSupport this conn pool strategy")
View Source
var ErrUnexpectedHeaderEOF = errors.New("http: unexpected EOF reading header")
View Source
var ErrUnexpectedReqBodyEOF = errors.New("http: unexpected EOF reading request body")
View Source
var ErrUnexpectedRespBodyEOF = errors.New("http: unexpected EOF reading response body")
View Source
var ErrUnexpectedTrailerEOF = errors.New("http: unexpected EOF reading trailer")
View Source
var ErrorInvalidURI = errors.New("invalid uri")
View Source
var FsCantCloseFileReader = errors.New("Fasthttp Fs serve: cannot close file reader")
View Source
var FsCantGetFileReader = errors.New("fasthttp Fs serve: can't get file reader")
View Source
var FsCantHandleBigFileErr = errors.New("fasthttp Fs serve: cant handle this size file on this platform")
View Source
var FsCantSeekByRangeError = errors.New("fasthttp Fs serve: can seek by range")
View Source
var FsDirIndexFileCantOpenErr = errors.New("fasthttp Fs serve: can't open directory index file")
View Source
var FsDotDotSlashInPathErr = errors.New("fasthttp Fs serve: '/../' in path")
View Source
var FsFileNotFoundErr = errors.New("fasthttp Fs serve: opened file not found")
View Source
var FsFileNotFoundOrCantOpenErr = errors.New("fasthttp Fs serve: file not found or can't open")
View Source
var FsNilByteInPathErr = errors.New("fasthttp Fs serve: nil byte in path")
View Source
var FsNotAllowedIndexDirErr = errors.New("fasthttp Fs serve: want visit dir")
View Source
var FsOpenedFileNotSeekableErr = errors.New("fasthttp Fs serve: opened file not seekable")
View Source
var FsPermissionDeniedErr = errors.New("fasthttp Fs serve: permission denied")
View Source
var FsRangeNotSatisfiableError = errors.New("fasthttp Fs serve: range not satisfiable")
View Source
var FsSeekStartNotZeroErr = errors.New("bug: File.Seek(0, io.SeekStart) returned (0, nil)")
View Source
var HeaderBufferSmallErr = errors.New("header buffer is too small")
View Source
var LinkBufferCap = block4k

LinkBufferCap that can be modified marks the minimum value of each node of LinkBuffer.

View Source
var MaxSmallFileSize int64 = 2 * 4096

MaxSmallFileSize Files bigger than this size are sent with sendfile.

View Source
var MultipleContentLengthErr = newHeaderParseErr("multiple Content-Length headers", "")
View Source
var TrailerHeaderBufferSmallErr = errors.New("trailer header buffer is too small")

Functions

func AcquireTimer

func AcquireTimer(timeout time.Duration) *time.Timer

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

func AddMissingPort(addr string, isTLS bool) string

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 AppendBrotliBytes

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

AppendBrotliBytes appends brotlied src to dst and returns the resulting dst.

func AppendBrotliBytesLevel

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

AppendBrotliBytesLevel appends brotlied src to dst using the given compression level and returns the resulting dst.

Supported compression levels are:

  • CompressBrotliNoCompression
  • CompressBrotliBestSpeed
  • CompressBrotliBestCompression
  • CompressBrotliDefaultCompression

func AppendDeflateBytes

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

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

func AppendDeflateBytesLevel

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

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

Supported compression levels are:

  • CompressNoCompression
  • CompressBestSpeed
  • CompressBestCompression
  • CompressDefaultCompression
  • CompressHuffmanOnly

func AppendGunzipBytes

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

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

func AppendGzipBytes

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

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

func AppendGzipBytesLevel

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

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

Supported compression levels are:

  • CompressNoCompression
  • CompressBestSpeed
  • CompressBestCompression
  • CompressDefaultCompression
  • CompressHuffmanOnly

func AppendHTMLEscape

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

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

func AppendHTMLEscapeBytes

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

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

func AppendHTTPDate

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

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

func AppendIPv4

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

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

func AppendInflateBytes

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

AppendInflateBytes appends inflated src to dst and returns the resulting dst.

func AppendNormalizedHeaderKey

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

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

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

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

func AppendNormalizedHeaderKeyBytes

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

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

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

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

func AppendQuotedArg

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

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

func AppendUint

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

AppendUint appends n to dst and returns the extended dst.

func AppendUintInto

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

func AppendUnbrotliBytes

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

AppendUnbrotliBytes appends unbrotlied src to dst and returns the resulting dst.

func AppendUnquotedArg

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

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

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

func AppendUnzstdBytes

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

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

func AppendZstdBytes

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

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

func AppendZstdBytesLevel

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

func BrotliReader

func BrotliReader(r io.Reader, level int) (newR io.ReadCloser)

func BrotliReaderPool

func BrotliReaderPool(r io.Reader, level int) (newR io.ReadCloser)

func DeflateReader

func DeflateReader(r io.Reader, level int) (newR io.ReadCloser)

func DeflateReaderPool

func DeflateReaderPool(r io.Reader, level int) (newR io.ReadCloser)

func Dial

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

Dial dials the given TCP addr using tcp4.

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

  • It reduces load on DNS resolver by caching resolved TCP addressed for 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

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

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

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

  • It reduces load on DNS resolver by caching resolved TCP addressed for 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

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

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

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

  • It reduces load on DNS resolver by caching resolved TCP addressed for 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

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

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

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

  • It reduces load on DNS resolver by caching resolved TCP addressed for 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

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

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

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

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

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

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

Response is ignored if resp is nil.

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

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

func DoDeadline

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

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

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

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

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

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

Response is ignored if resp is nil.

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

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

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

func DoRedirects

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

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

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

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

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

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

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

Response is ignored if resp is nil.

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

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

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

func FileLastModified

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

FileLastModified returns last modified time for the file.

func GenerateTestCertificate

func GenerateTestCertificate(host string) ([]byte, []byte, error)

GenerateTestCertificate generates a test certificate and private key based on the given host.

func Get

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

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 GzipReader

func GzipReader(r io.Reader, level int) (newR io.Reader)

func GzipReaderPool

func GzipReaderPool(r io.Reader, level int) (newR io.ReadCloser)

func HasAcceptEncodingBytes

func HasAcceptEncodingBytes(ae []byte, acceptEncoding []byte) bool

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

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

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

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

func ListenAndServeTLSEmbed

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

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

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

func ListenAndServeUNIX

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 NewBigFileReaderPool

func NewBigFileReaderPool(count int) *fsFilePool

NewBigFileReaderPool count is File copy limit

func NewIOReadWriter

func NewIOReadWriter(rw ReadWriter) io.ReadWriter

NewIOReadWriter convert ReadWriter to io.ReadWriter

func NewIOReader

func NewIOReader(r Reader) io.Reader

NewIOReader convert Reader to io.Reader

func NewIOWriter

func NewIOWriter(w Writer) io.Writer

NewIOWriter convert Writer to io.Writer

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

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

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

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

func ParseHTTPDate

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

ParseHTTPDate parses HTTP-compliant (RFC1123) date.

func ParseIPv4

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

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

func ParseUfloat

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

ParseUfloat parses unsigned float from buf.

func ParseUint

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

ParseUint parses uint from buf.

func Post

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

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

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

func ReleaseTimer(t *time.Timer)

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/valyala/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) (err 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 ServeTLS

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

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

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

func ServeTLSEmbed

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

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

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

func 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. When the Body of a Request and Response is reset, if the underlying slice's capacity exceeds the set value, it will not be returned to the cache pool but will instead be set to nil.

A value of 0 or negative indicates that it will always be released to the cache pool.

func StatusCodeIsRedirect

func StatusCodeIsRedirect(statusCode int) bool

StatusCodeIsRedirect returns true if the status code indicates a redirect.

func StatusMessage

func StatusMessage(statusCode int) string

StatusMessage returns HTTP status message for the given status code.

func VisitHeaderParams

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

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

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

func WriteBrotli

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

WriteBrotli writes brotlied p to w and returns the number of compressed bytes written to w.

func WriteBrotliLevel

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

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

Supported compression levels are:

  • CompressBrotliNoCompression
  • CompressBrotliBestSpeed
  • CompressBrotliBestCompression
  • CompressBrotliDefaultCompression

func WriteDeflate

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

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

func WriteDeflateLevel

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

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

Supported compression levels are:

  • CompressNoCompression
  • CompressBestSpeed
  • CompressBestCompression
  • CompressDefaultCompression
  • CompressHuffmanOnly

func WriteGunzip

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

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

func WriteGzip

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

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

func WriteGzipLevel

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

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

Supported compression levels are:

  • CompressNoCompression
  • CompressBestSpeed
  • CompressBestCompression
  • CompressDefaultCompression
  • CompressHuffmanOnly

func WriteInflate

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

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

func WriteMultipartForm

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

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

func WriteUnbrotli

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

WriteUnbrotli writes unbrotlied p to w and returns the number of uncompressed bytes written to w.

func WriteUnzstd

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

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

func WriteZstdLevel

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

func ZstdReader

func ZstdReader(r io.Reader, level int) (newR io.ReadCloser)

func ZstdReaderPool

func ZstdReaderPool(r io.Reader, level int) (newR io.ReadCloser)

Types

type AbsoluteTime

type AbsoluteTime int64

type Args

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

Args represents query arguments.

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

Args instance MUST NOT be used from concurrently running goroutines.

func AcquireArgs

func AcquireArgs() *Args

AcquireArgs returns an empty Args object from the pool.

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

func (*Args) Add

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

Add adds 'key=value' argument.

Multiple values for the same key may be added.

func (*Args) AddBytesK

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

AddBytesK adds 'key=value' argument.

Multiple values for the same key may be added.

func (*Args) AddBytesKNoValue

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

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

Multiple values for the same key may be added.

func (*Args) AddBytesKV

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

AddBytesKV adds 'key=value' argument.

Multiple values for the same key may be added.

func (*Args) AddBytesV

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

AddBytesV adds 'key=value' argument.

Multiple values for the same key may be added.

func (*Args) AddNoValue

func (a *Args) AddNoValue(key string)

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

Multiple values for the same key may be added.

func (*Args) AppendBytes

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

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

func (*Args) CopyTo

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

CopyTo copies all args to dst.

func (*Args) Del

func (a *Args) Del(key string)

Del deletes argument with the given key from query args.

func (*Args) DelBytes

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

DelBytes deletes argument with the given key from query args.

func (*Args) GetBool

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

GetBool returns boolean value for the given key.

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

func (*Args) GetUfloat

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

GetUfloat returns ufloat value for the given key.

func (*Args) GetUfloatOrZero

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

GetUfloatOrZero returns ufloat value for the given key.

Zero (0) is returned on error.

func (*Args) GetUint

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

GetUint returns uint value for the given key.

func (*Args) GetUintOrZero

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

GetUintOrZero returns uint value for the given key.

Zero (0) is returned on error.

func (*Args) Has

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

Has returns true if the given key exists in Args.

func (*Args) HasBytes

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

HasBytes returns true if the given key exists in Args.

func (*Args) Len

func (a *Args) Len() int

Len returns the number of query args.

func (*Args) Parse

func (a *Args) Parse(s string)

Parse parses the given string containing query args.

func (*Args) ParseBytes

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

ParseBytes parses the given b containing query args.

func (*Args) Peek

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

Peek returns query arg value for the given key.

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

func (*Args) PeekBytes

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

PeekBytes returns query arg value for the given key.

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

func (*Args) PeekMulti

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

PeekMulti returns all the arg values for the given key.

func (*Args) PeekMultiBytes

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

PeekMultiBytes returns all the arg values for the given key.

func (*Args) QueryString

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

QueryString returns query string for the args.

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

func (*Args) Reset

func (a *Args) Reset()

Reset clears query args.

func (*Args) Set

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

Set sets 'key=value' argument.

func (*Args) SetBytesK

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

SetBytesK sets 'key=value' argument.

func (*Args) SetBytesKNoValue

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

SetBytesKNoValue sets 'key' argument.

func (*Args) SetBytesKV

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

SetBytesKV sets 'key=value' argument.

func (*Args) SetBytesV

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

SetBytesV sets 'key=value' argument.

func (*Args) SetNoValue

func (a *Args) SetNoValue(key string)

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

Only key in argument, like key1&key2.

func (*Args) SetUint

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

SetUint sets uint value for the given key.

func (*Args) SetUintBytes

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

SetUintBytes sets uint value for the given key.

func (*Args) Sort

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

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

For example args.Sort(bytes.Compare).

func (*Args) String

func (a *Args) String() string

String returns string representation of query args.

func (*Args) VisitAll

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

VisitAll calls f for each existing arg.

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

func (*Args) WriteTo

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

WriteTo writes query string to w.

WriteTo implements io.WriterTo interface.

type 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 BufferedChunkedWriter

type BufferedChunkedWriter struct {
	*pbufio.Writer
}

func (BufferedChunkedWriter) Flush

func (bw BufferedChunkedWriter) Flush() (err error)

func (BufferedChunkedWriter) Write

func (bw BufferedChunkedWriter) Write(b []byte) (n int, err error)

type BufferedCompressWriter

type BufferedCompressWriter struct {
	*pbufio.Writer
}

BufferedCompressWriter Some compression algorithms produce very small output blocks. In such cases, these small blocks are cached and only flushed to the underlying `Writer` when `Flush` is called or when the cache is full.

func (BufferedCompressWriter) Flush

func (bw BufferedCompressWriter) Flush() (err error)

func (BufferedCompressWriter) Write

func (bw BufferedCompressWriter) Write(b []byte) (n int, err error)

type BufioReaderPooler

type BufioReaderPooler interface {
	Get() *bufio.Reader
	Put(b *bufio.Reader)
}

type BufioWriterPooler

type BufioWriterPooler interface {
	Get() *bufio.Writer
	Put(b *bufio.Writer)
}

type CacheKind

type CacheKind uint8

type ChunkWriter

type ChunkWriter struct {
	*bufio.Writer
}

ChunkWriter Write content to the underlying `Writer` using chunked encoding.

func (ChunkWriter) Write

func (w ChunkWriter) Write(b []byte) (n int, err error)

Write the parameter `p` to the underlying `Writer` using chunked encoding. If the length of `p` is 0, write nothing.

type ChunkedWriter

type ChunkedWriter struct {
	*bufio.Writer
}

func (ChunkedWriter) Flush

func (w ChunkedWriter) Flush() error

func (ChunkedWriter) SubFlush

func (w ChunkedWriter) SubFlush() error

func (ChunkedWriter) Write

func (w ChunkedWriter) Write(b []byte) (n int, err error)

type CleanItem

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

type CleanThresholdFunc

type CleanThresholdFunc func(t1, t2, t3, t4 *time.Time, readyLen, maxWorkersCount int, maxIdleWorkerDuration time.Duration) (cleanNum int)

CleanThresholdFunc t1, t2, t3 and t4 are 1/8 1/4 1/2 3/4 workerChan's lastUseTime respectively. cleanNum is the number of workerChan to clean. zero represents no op.

type CleanableItem

type CleanableItem interface {
	Clean() (duration time.Duration, stop bool)
}

type Client

type Client struct {
	Config

	// ConfigureClient configures the fasthttp.HostClient.
	ConfigureClient func(hc *HostClient) error
	// 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) AddHostClient

func (c *Client) AddHostClient(host string, hc *HostClient)

func (*Client) Clean

func (c *Client) Clean() (du time.Duration, stop bool)

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

func (c *Client) Dedicated(f func(conn net.Conn) bool, host []byte, dialTimeout, writeTimeout time.Duration, isTLS bool) (err error)

Dedicated acquire a con from HostClient pool according tls and host, call f with this con. If f return false closing this con, true return this con to pool. dialTimeout is timeout of create a con if without free con. writeTimeout is timeout of tls handshake.

func (*Client) Do

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

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

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

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

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

Response is ignored if resp is nil.

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

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

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

func (*Client) DoDeadline

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

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

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

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

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

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

Response is ignored if resp is nil.

ErrTimeout is returned if the response wasn't returned until the given deadline. 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

func (c *Client) 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 (*Client) DoTimeout

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

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

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

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

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

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

Response is ignored if resp is nil.

ErrTimeout is returned if the response wasn't returned during the given timeout. 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

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

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

func (c *Client) HostClient(host string, isTls bool) (hc *HostClient)

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 CloseReason

type CloseReason int32
const (
	ReadTimeout CloseReason
	WriteTimeout
	IdleTimeout
	ShutDownTimeout
	ShutDownNormal
)

type CompressAlg

type CompressAlg int8
const (
	Gzip CompressAlg
	Br
	Deflate
	Zstd
)

CompressAlg is a compression algorithm Zero value means no compression.

type CompressConfig

type CompressConfig struct {
	Algs   [4]CompressAlg
	Levels [4]int8
}

CompressConfig Mapping of compression algorithms to levels Support gzip, deflate, brotli, zstd

type CompressInfo

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

type CompressInfoChan

type CompressInfoChan chan *CompressInfo

type CompressWriter

type CompressWriter struct {
	compress.Writer
	// contains filtered or unexported fields
}

CompressWriter Output the content using the `compress.Writer` algorithm to `wf`. This structure is only applicable to compression algorithms that require caching.

func (CompressWriter) Close

func (cw CompressWriter) Close() (err error)

Close the compressor and flush the contents in the underlying cache.

func (CompressWriter) Flush

func (cw CompressWriter) Flush() (err error)

Flush the contents in the compressor and also flush the contents in the target cache. The target attribute is `cw`, which will encode these contents in Chunked format.

type Config

type Config struct {
	// When omitted, the client's global bufioReader cache pool will be used.
	ReaderPool BufioReaderPooler
	// When omitted, the client's global bufioWriter cache pool will be used.
	WriterPool BufioWriterPooler
	// Use the global DefaultTransport when omitted.
	Transport RoundTripper
	// A zero value is DefaultDialTimeout
	// A negative value indicates no timeout limit.
	DialTimeout time.Duration
	// A negative value indicates no timeout limit.
	// This field is only considered when the `Request.ReadTimeout` method returns a value of 0.
	// The Request.timeout field value is only considered when this field is set to 0.
	ReadTimeout time.Duration
	// A negative value indicates no timeout limit.
	// This field is only considered when the `Request.ReadTimeout` method returns a value of 0.
	// The Request.timeout field value is only considered when this field is set to 0.
	WriteTimeout time.Duration
	// Zero and negative value indicates no time limit.
	// Connection's life time.
	// However, it is done by first sending the `Connection: close` request header and then closing
	// the connection only after reading the response.
	MaxConnDuration time.Duration
	// Zero value represents DefaultMaxIdleConnDuration.
	// Negative value indicates no time limit.
	MaxIdleConnDuration time.Duration
	// Zero value indicates that ErrNoFreeConns error is returned immediately when the MaxConns limit is reached.
	// Negative value indicates no time limit.
	MaxConnWaitTimeout time.Duration
	// Zero value and negative value indicate that this time interval is determined by the operating system.
	TCPKeepalivePeriod time.Duration
	// Negative value means no limit.
	// Zero value indicates the use of DefaultMaxConnsPerHost.
	MaxConns int
	// Zero value and negative value indicate the use of DefaultMaxIdemponentCallAttempts
	MaxIdemponentCallAttempts int
	// When the client encounters an error during a request, the behavior—whether to retry,
	// whether to retry later, or whether to reset the request timeout—should be determined
	// based on the return value of this interface.
	// This field is only effective within the range of MaxIdemponentCallAttempts.
	RetryIf RetryIfErrFunc
	// Zero value or negative value indicates no limit.
	MaxResponseBodySize int
	// Zero value and negative value indicate using defaultReadBufferSize: 4096.
	ReadBufferSize int
	// Zero value and negative value indicate using defaultWriteBufferSize: 4096.
	WriteBufferSize int
	// Zero value indicates the use of defaultDialerV2.
	Dial Dialer
	// Zero value indicates the use of default configuration.
	TLSConfig *tls.Config
	// This field must be set; it specifies the list of dial addresses.
	Addrs []string
	// Obtain idle connection policy
	// Zero value represents FIFO
	ConnPoolStrategy ConnPoolStrategyType
	// When the UserAgent header is not set, this field serves as the default value.
	Name string
	// The global `defaultUserAgent: fasthttp` will only be considered when Name field is zero value.
	NoDefaultUserAgentHeader bool
	// Use the TCP network protocol for dialing instead of TCP4.
	DialDualStack bool
	// Whether to use TLS for communication with the target address
	IsTLS bool
	// Whether the sent request headers need to be normalized
	DisableHeaderNamesNormalizing bool
	// Whether to encode the request path
	DisablePathNormalizing bool
	// Whether the log information exposes communication data
	SecureErrorLogMessage bool
	// Read client request and response as a stream
	StreamResponseBody bool
	// Whether the operating system should send tcp keep-alive messages on the tcp connection.
	//
	// By default, tcp keep-alive connections are disabled.
	TCPKeepalive          bool
	DifferentHostRedirect bool
}

type ConnPoolStrategyType

type ConnPoolStrategyType int

ConnPoolStrategyType define strategy of connection pool enqueue/dequeue.

const (
	FIFO ConnPoolStrategyType = iota
	LIFO
)

type ConnState

type ConnState int32

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

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

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

func (ConnState) String

func (c ConnState) String() string

type ConnStatus

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

ConnStatus is used to store the status of a connection throughout its entire lifecycle.

conns status may is one of StateNew StateIdle StateClosed StateActiveR StateActiveW StateHijacked at some a time point.

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

Cookie represents HTTP response cookie.

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

Cookie instance MUST NOT be used from concurrently running goroutines.

func AcquireCookie

func AcquireCookie() *Cookie

AcquireCookie returns an empty Cookie object from the pool.

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

func (*Cookie) AppendBytes

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

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

func (*Cookie) Cookie

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

Cookie returns cookie representation.

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

func (*Cookie) CopyTo

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

CopyTo copies src cookie to c.

func (*Cookie) Domain

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

Domain returns cookie domain.

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

func (*Cookie) Expire

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

Expire returns cookie expiration time.

CookieExpireUnlimited is returned if cookie doesn't expire.

func (*Cookie) HTTPOnly

func (c *Cookie) HTTPOnly() bool

HTTPOnly returns true if the cookie is http only.

func (*Cookie) Key

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

Key returns cookie name.

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

func (*Cookie) MaxAge

func (c *Cookie) MaxAge() int

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

func (*Cookie) Parse

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

Parse parses Set-Cookie header.

func (*Cookie) ParseBytes

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

ParseBytes parses Set-Cookie header.

func (*Cookie) Partitioned

func (c *Cookie) Partitioned() bool

Partitioned returns true if the cookie is partitioned.

func (*Cookie) Path

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

Path returns cookie path.

func (*Cookie) Reset

func (c *Cookie) Reset()

Reset clears the cookie.

func (*Cookie) SameSite

func (c *Cookie) SameSite() CookieSameSite

SameSite returns the SameSite mode.

func (*Cookie) Secure

func (c *Cookie) Secure() bool

Secure returns true if the cookie is secure.

func (*Cookie) SetDomain

func (c *Cookie) SetDomain(domain string)

SetDomain sets cookie domain.

func (*Cookie) SetDomainBytes

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

SetDomainBytes sets cookie domain.

func (*Cookie) SetExpire

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

SetExpire sets cookie expiration time.

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

By default cookie lifetime is limited by browser session.

func (*Cookie) SetHTTPOnly

func (c *Cookie) SetHTTPOnly(httpOnly bool)

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

func (*Cookie) SetKey

func (c *Cookie) SetKey(key string)

SetKey sets cookie name.

func (*Cookie) SetKeyBytes

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

SetKeyBytes sets cookie name.

func (*Cookie) SetMaxAge

func (c *Cookie) SetMaxAge(seconds int)

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

Set max age to 0 to unset.

func (*Cookie) SetPartitioned

func (c *Cookie) SetPartitioned(partitioned bool)

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

func (*Cookie) SetPath

func (c *Cookie) SetPath(path string)

SetPath sets cookie path.

func (*Cookie) SetPathBytes

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

SetPathBytes sets cookie path.

func (*Cookie) SetPrefixValue

func (c *Cookie) SetPrefixValue(prefix string, value string)

SetPrefixValue sets cookie value.

func (*Cookie) SetPrefixValueBytes

func (c *Cookie) SetPrefixValueBytes(prefix []byte, value []byte)

SetPrefixValueBytes sets cookie value.

func (*Cookie) SetSameSite

func (c *Cookie) SetSameSite(mode CookieSameSite)

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

func (*Cookie) SetSecure

func (c *Cookie) SetSecure(secure bool)

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

func (*Cookie) SetValue

func (c *Cookie) SetValue(value string)

SetValue sets cookie value.

func (*Cookie) SetValueBytes

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

SetValueBytes sets cookie value.

func (*Cookie) String

func (c *Cookie) String() string

String returns cookie representation.

func (*Cookie) Value

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

Value returns cookie value.

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

func (*Cookie) WriteTo

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

WriteTo writes cookie representation to w.

WriteTo implements io.WriterTo interface.

type CookieSameSite

type CookieSameSite int

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

const (
	// CookieSameSiteDisabled removes the SameSite flag.
	CookieSameSiteDisabled CookieSameSite = iota
	// CookieSameSiteDefaultMode sets the SameSite flag.
	CookieSameSiteDefaultMode
	// CookieSameSiteLaxMode sets the SameSite flag with the "Lax" parameter.
	CookieSameSiteLaxMode
	// CookieSameSiteStrictMode sets the SameSite flag with the "Strict" parameter.
	CookieSameSiteStrictMode
	// CookieSameSiteNoneMode sets the SameSite flag with the "None" parameter.
	// See https://tools.ietf.org/html/draft-west-cookie-incrementalism-00
	CookieSameSiteNoneMode // third-party cookies are phasing out, use Partitioned cookies instead
)

type DefaultLogger

type DefaultLogger struct {
	*log.Logger
}

func (DefaultLogger) Write

func (l DefaultLogger) Write(b []byte)

type DialFunc

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

DialFunc must establish connection to addr.

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

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

  • foobar.com:80
  • foobar.com:443
  • foobar.com:8080

type DialFuncWithTimeout

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

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 Dialer

type Dialer func(network string, addr string, timeout time.Duration) (net.Conn, error)

type DurationCleaner

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

func (*DurationCleaner) Register

func (cc *DurationCleaner) Register(client CleanableItem, duration time.Duration)

func (*DurationCleaner) Stop

func (cc *DurationCleaner) Stop()

type ErrBrokenChunk

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

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

type ErrDialWithUpstream

type ErrDialWithUpstream struct {
	Upstream string
	// contains filtered or unexported fields
}

ErrDialWithUpstream wraps dial error with upstream info.

Should use errors.As to get upstream information from error:

hc := fasthttp.HostClient{Addr: "foo.com,bar.com"}
err := hc.Do(req, res)

var dialErr *fasthttp.ErrDialWithUpstream
if errors.As(err, &dialErr) {
	upstream = dialErr.Upstream // 34.206.39.153:80
}

func (*ErrDialWithUpstream) Error

func (e *ErrDialWithUpstream) Error() string

func (*ErrDialWithUpstream) Unwrap

func (e *ErrDialWithUpstream) Unwrap() error

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 ErrStreamSendSizeNotMatch

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

func (*ErrStreamSendSizeNotMatch) Error

func (es *ErrStreamSendSizeNotMatch) Error() string

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 to the root directory to serve files from.
	Root string

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

	// Path to the compressed root directory to serve files from. If this value
	// is empty, Root is used.
	CompressRoot string

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

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

	// 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
	Orders [3]compress.Order
	Levels [3]compress.Level

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

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

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

	// Suffixes list to add to compressedFileSuffix depending on encoding
	//
	// This value has sense only if Compress is set.
	//
	// DefaultCompressedFileSuffixes is used by default.
	CompressedFileSuffixes [3]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{}

	NeedCompressFunc func(path []byte) bool
	NeedCompressSize int64
	// 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/valyala/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.

func (*FS) NewRequestHandlerWithError

func (fs *FS) NewRequestHandlerWithError() RequestHandlerWithError

type FileLocks

type FileLocks struct {
	xsync.MapOf[string, *sync.Mutex]
}

func (*FileLocks) Locker

func (fl *FileLocks) Locker(path string) *sync.Mutex

type FileSeeker

type FileSeeker interface {
	fs.File
	io.Seeker
}

FileSeeker The request file type must implement this interface. Excludes directory index content

type FormValueFunc

type FormValueFunc func(*RequestCtx, string) []byte

type FsWhenCompressErr

type FsWhenCompressErr struct {
	Path string
	// contains filtered or unexported fields
}

func (FsWhenCompressErr) Error

func (we FsWhenCompressErr) Error() string

func (FsWhenCompressErr) Unwrap

func (we FsWhenCompressErr) Unwrap() error

type HTTPError

type HTTPError string

type HeaderParseErr

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

func (*HeaderParseErr) Error

func (h *HeaderParseErr) Error() string

type HijackHandler

type HijackHandler func(c net.Conn)

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 {
	// 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/newacorn/fasthttp"
)

func main() {
	// Prepare a client, which fetches webpages via HTTP proxy listening
	// on the localhost:8080.
	c, err := fasthttp.NewHostClient(fasthttp.Config{
		Addrs: []string{"localhost:8080"},
	})
	if err != nil {
		log.Fatal(err)
	}
	// 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 NewHostClient

func NewHostClient(config Config) (hc *HostClient, err error)

func (*HostClient) Clean

func (c *HostClient) Clean() (sleepDuration time.Duration, stop bool)

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

func (c *HostClient) Dedicated(f func(conn net.Conn) bool, dialTimeout, writeTimeout time.Duration) (err error)

Dedicated acquire a con from HostClient pool, call f with this con. If f return false closing this con, true return this con to pool. dialTimeout is timeout of create a con if without free con. writeTimeout is timeout of tls handshake.

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

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

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

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

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

Response is ignored if resp is nil.

ErrTimeout is returned if the response wasn't returned until the given deadline. 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

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

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

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

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

Response is ignored if resp is nil.

ErrTimeout is returned if the response wasn't returned during the given timeout. 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

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

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.

func (*HostClient) Transport

func (c *HostClient) Transport() RoundTripper

type InvalidHostError

type InvalidHostError string

func (InvalidHostError) Error

func (e InvalidHostError) Error() string

type LBClient

type LBClient struct {

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

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

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

LBClient balances requests among available LBClient.Clients.

It has the following features:

  • Balances load among available clients using 'least loaded' + '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.NewHostClient(fasthttp.Config{
		Addrs: []string{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

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

Do calculates timeout using LBClient.Timeout and calls DoTimeout on the least loaded client.

func (*LBClient) DoDeadline

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

DoDeadline calls DoDeadline on the least loaded client.

func (*LBClient) DoTimeout

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

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 LinkBuffer

type LinkBuffer = UnsafeLinkBuffer

func NewLinkBuffer

func NewLinkBuffer(size ...int) *LinkBuffer

NewLinkBuffer size defines the initial capacity, but there is no readable data.

type Logger

type Logger interface {
	// Printf must have the same semantics as log.Printf.
	Printf(format string, args ...any)
	Write(b []byte)
}

Logger is used for logging formatted messages.

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: ""
  • slashesCount = 3, original path: "/foo/bar", result: ""
  • slashesCount = 1, original path: "/foo", 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"

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

  • host=img.aaa.com/sub, slashesCount=1, original path="/456.jpg" Resulting path: "/invalid-host"

type PeekOneByteErr

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

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.
	DialTimeout time.Duration
	Dial        Dialer

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

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

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

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

The function doesn't follow redirects.

Response is ignored if resp is nil.

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

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

func (*PipelineClient) DoTimeout

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

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

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

The function doesn't follow redirects.

Response is ignored if resp is nil.

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

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

func (*PipelineClient) PendingRequests

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 ReadBodyErr

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

func (*ReadBodyErr) Error

func (e *ReadBodyErr) Error() string

type ReadCloserWithError

type ReadCloserWithError interface {
	io.Reader
	CloseWithError(err error) error
}

ReadCloserWithError Used by the client, when processing a response as a stream. If an error is detected when closing the stream, the `CloseWithError` method is called to determine whether to release or close the underlying connection.

type ReadWriter

type ReadWriter interface {
	Reader
	Writer
}

ReadWriter is a combination of Reader and Writer.

func NewReadWriter

func NewReadWriter(rw io.ReadWriter) ReadWriter

NewReadWriter convert io.ReadWriter to nocopy ReadWriter

type Reader

type Reader interface {
	// Next returns a slice containing the next n bytes from the buffer,
	// advancing the buffer as if the bytes had been returned by Read.
	//
	// If there are fewer than n bytes in the buffer, Next returns will be blocked
	// until data enough or an error occurs (such as a wait timeout).
	//
	// The slice p is only valid until the next call to the Release method.
	// Next is not globally optimal, and Skip, ReadString, ReadBinary methods
	// are recommended for specific scenarios.
	//
	// Return: len(p) must be n or 0, and p and error cannot be nil at the same time.
	Next(n int) (p []byte, err error)

	// Peek returns the next n bytes without advancing the reader.
	// Other behavior is the same as Next.
	Peek(n int) (buf []byte, err error)

	// Skip the next n bytes and advance the reader, which is
	// a faster implementation of Next when the next data is not used.
	Skip(n int) (err error)

	// Until reads until the first occurrence of delim in the input,
	// returning a slice stops with delim in the input buffer.
	// If Until encounters an error before finding a delimiter,
	// it returns all the data in the buffer and the error itself (often ErrEOF or ErrConnClosed).
	// Until returns err != nil only if line does not end in delim.
	Until(delim byte) (line []byte, err error)

	// ReadString is a faster implementation of Next when a string needs to be returned.
	// It replaces:
	//
	//  var p, err = Next(n)
	//  return string(p), err
	//
	ReadString(n int) (s string, err error)

	// ReadBinary is a faster implementation of Next when it needs to
	// return a copy of the slice that is not shared with the underlying layer.
	// It replaces:
	//
	//  var p, err = Next(n)
	//  var b = make([]byte, n)
	//  copy(b, p)
	//  return b, err
	//
	ReadBinary(n int) (p []byte, err error)

	// ReadByte is a faster implementation of Next when a byte needs to be returned.
	// It replaces:
	//
	//  var p, err = Next(1)
	//  return p[0], err
	//
	ReadByte() (b byte, err error)

	// Slice returns a new Reader containing the Next n bytes from this Reader.
	//
	// If you want to make a new Reader using the []byte returned by Next, Slice already does that,
	// and the operation is zero-copy. Besides, Slice would also Release this Reader.
	// The logic pseudocode is similar:
	//
	//  var p, err = this.Next(n)
	//  var reader = new Reader(p) // pseudocode
	//  this.Release()
	//  return reader, err
	//
	Slice(n int) (r Reader, err error)

	// Release the memory space occupied by all read slices. This method needs to be executed actively to
	// recycle the memory after confirming that the previously read data is no longer in use.
	// After invoking Release, the slices obtained by the method such as Next, Peek, Skip will
	// become an invalid address and cannot be used anymore.
	Release() (err error)

	// Len returns the total length of the readable data in the reader.
	Len() (length int)
}

Reader is a collection of operations for nocopy reads.

For ease of use, it is recommended to implement Reader as a blocking interface, rather than simply fetching the buffer. For example, the return of calling Next(n) should be blocked if there are fewer than n bytes, unless timeout. The return value is guaranteed to meet the requirements or an error will be returned.

func NewReader

func NewReader(r io.Reader) Reader

NewReader convert io.Reader to nocopy Reader

type RecycleItemser

type RecycleItemser interface {
	RecycleItems()
}

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
	//
	// When this field is `true` and `RequestHeader.host` is not empty and parsedURI is true,
	// use `RequestHeader.host` as the value for the `Host` request header.
	//
	// When `RequestHeader.host` is empty and parsedURI is true, use uri's Host.
	//
	// Otherwise, use RequestHeader.host.
	UseHostHeader bool

	// Whether to format the request path when using the redirect path obtained from the `Location` header.
	// Used only for the client, only in doRequestFollowRedirects function,
	DisableRedirectPathNormalizing bool

	// Used only for the server. When closing the request's bodyStream, whether to discard the content
	// of the streaming request body to avoid disrupting keep-alive connections and
	// interfering with the reading of the next request.
	// Inherits the value from the `Server.DiscardUnReadRequestBodyStream` field.
	DiscardUnReadBodyStream bool

	// Whether the request body is read in a streaming manner is applicable only to the server side.
	StreamBody bool
	// contains filtered or unexported fields
}

Request represents HTTP request. It can be used to represent a request both on the server side and on the client side.

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

Request instance MUST NOT be used from concurrently running goroutines.

Client: To send a `multipart/form-data` request, only set `multipartForm` and its fields. To send an `application/x-www-form-urlencoded` request, only set the `postArgs` field. For the above two request types, the `Content-Type` request header will be set automatically. Other request type's Content-Type must be set manually.

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

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

AppendBody appends p to request body.

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

func (*Request) AppendBodyString

func (req *Request) AppendBodyString(s string)

AppendBodyString appends s to request body.

func (*Request) Body

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

Body returns request body.

The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead. Return the request body in the following order: `bodyStream`, `bodyRaw`, `body` field. Include multipart/form-data body and x-www-form-urlencoded/application form body. 与Server.SetRequestBodyStream搭配使用时,Body()最多返回Server.MaxRequestBodySize个字节。

The returned body is a reference and remains valid until the body in the `Request` is modified. If an error occurs while closing the body stream, the error is returned as the content of the body.

The `bodyStream` will always be closed, so it is recommended to handle `bodyStream` separately. If `maxBodySize` is not set, it may result in a memory overflow.

Each time the result is the same, it will be cached in the `body` field.

func (*Request) BodyGunzip

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

BodyGunzip returns un-gzipped body data.

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

Use Body for reading gzipped request body. The `body` content will always be decompressed, regardless of the `Content-Encoding`.

func (*Request) BodyInflate

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

BodyInflate returns inflated body data.

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

func (*Request) BodyStream

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

BodyStream returns io.Reader.

You must CloseBodyStream or ReleaseRequest after you use it.

func (*Request) BodyUnbrotli

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

BodyUnbrotli returns un-brotlied body data.

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

The `body` content will always be decompressed, regardless of the `Content-Encoding`.

func (*Request) BodyUncompressed

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

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

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

func (*Request) BodyWithError

func (req *Request) BodyWithError() (body []byte, err error)

BodyWithError 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. Return the request body in the following order: `bodyStream`, `bodyRaw`, `body` field. Include multipart/form-data body and x-www-form-urlencoded/application form body. 与Server.SetRequestBodyStream搭配使用时,Body()最多返回Server.MaxRequestBodySize个字节。

The returned body is a reference and remains valid until the body in the `Request` is modified. If an error occurs while closing the body stream.

If the `bodyStream` field is not empty, the size of the content read is limited by the `maxBodySize` field.

The `bodyStream` will always be closed, so it is recommended to handle `bodyStream` separately. If `maxBodySize` is not set, it may result in a memory overflow.

Each time the result is the same, it will be cached in the `body` field.

func (*Request) BodyWriteTo

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

BodyWriteTo writes request Body() to w. In bodyStream multipart/form-data rawBody body x-www-form-urlencoded/application orders.

func (*Request) BodyWriter

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

BodyWriter Write the request body into the `Request.body` field using the `io.Writer` interface.

func (*Request) CloseBodyStream

func (req *Request) CloseBodyStream() error

func (*Request) ConnectionClose

func (req *Request) ConnectionClose() bool

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

func (*Request) CopyTo

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

CopyTo copies req contents to dst except of body stream.

func (*Request) Host

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

Host returns the host for the given request.

func (*Request) IsBodyStream

func (req *Request) IsBodyStream() bool

IsBodyStream returns true if body is set via SetBodyStream*.

func (*Request) KeepBuffer

func (req *Request) KeepBuffer() bool

func (*Request) MaxAttempts

func (req *Request) MaxAttempts() int

MaxAttempts The maximum number of attempts the client can make when sending a request, with the first send counting as one attempt.

func (*Request) MayContinue

func (req *Request) MayContinue() bool

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

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

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

func (*Request) MultipartForm

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

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

func (req *Request) PostArgs() *Args

PostArgs returns POST arguments.

func (*Request) Read

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

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

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

If MayContinue returns true, the caller must:

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

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

func (*Request) ReadBody

func (req *Request) ReadBody(r *bufio.Reader, maxBodySize int64, preParseMultipartForm ...bool) (err error)

ReadBody reads request's header and 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) ReadBodyStream

func (req *Request) ReadBodyStream(r *bufio.Reader, maxBodySize int64, preParseMultipartForm ...bool) (err error)

ReadBodyStream 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) ReadLimit

func (req *Request) ReadLimit(r *bufio.Reader, maxBodySize int64) (err error)

ReadLimit 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 ReadBody.
  • Or close the connection.

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

func (*Request) ReadTimeout

func (req *Request) ReadTimeout() time.Duration

func (*Request) ReleaseBody

func (req *Request) ReleaseBody(size int)

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

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

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

func (*Request) RemoveMultipartFormFiles

func (req *Request) RemoveMultipartFormFiles()

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

func (*Request) RequestURI

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

RequestURI returns request's URI.

func (*Request) Reset

func (req *Request) Reset()

Reset clears request contents. Expect keepBodyBuffer unchanged.

func (*Request) ResetBody

func (req *Request) ResetBody()

ResetBody resets request body.

func (*Request) RetryIf

func (req *Request) RetryIf() RetryIfErrFunc

RetryIf Used by the client to determine whether to retry when an error occurs while sending a request. Subject to the remaining attempts included in `MaxAttempts`.

func (*Request) SetBody

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

SetBody sets request body.

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

func (*Request) SetBodyRaw

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

SetBodyRaw sets response body, but without copying it.

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

func (*Request) SetBodyStream

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

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

func (req *Request) SetBodyString(body string)

SetBodyString sets request body.

func (*Request) SetConnectionClose

func (req *Request) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*Request) SetHost

func (req *Request) SetHost(host string)

SetHost sets host for the request.

func (*Request) SetHostBytes

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

SetHostBytes sets host for the request.

func (*Request) SetKeepBuffer

func (req *Request) SetKeepBuffer(keep bool)

SetKeepBuffer Whether to return the storage slices to the cache pool when the Request object is reset

func (*Request) SetMaxAttempts

func (req *Request) SetMaxAttempts(attempts int)

func (*Request) SetReadTimeout

func (req *Request) SetReadTimeout(timeout time.Duration)

SetReadTimeout Timeout for the client when reading the response body. A negative value indicates no timeout, and a zero value indicates using the corresponding value from `HostClient` or `Client`.

func (*Request) SetRequestURI

func (req *Request) SetRequestURI(requestURI string)

SetRequestURI sets RequestURI. Only applicable to the client.

func (*Request) SetRequestURIBytes

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

SetRequestURIBytes sets RequestURI. Only applicable to the client.

func (*Request) SetRetryIf

func (req *Request) SetRetryIf(f RetryIfErrFunc)

func (*Request) SetTimeout

func (req *Request) SetTimeout(t time.Duration)

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

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

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

func (*Request) SetWriteTimeout

func (req *Request) SetWriteTimeout(timeout time.Duration)

SetWriteTimeout Timeout for the client when sending the response body. A negative value indicates no timeout, and a zero value indicates using the corresponding value from `HostClient` or `Client`.

func (*Request) String

func (req *Request) String() string

String returns request representation include header and boy.

Returns error message instead of request representation on error.

Use Write instead of String for performance-critical code.

func (*Request) SwapBody

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

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

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

The `bodyStream` will always be closed, and if an error occurs during the closing, the error will be returned as the value.

The parameter `body` will exist as the underlying slice of the `body`. The return value is not a reference, and the parameter `body` cannot be used by the caller anymore.

func (*Request) URI

func (req *Request) URI() *URI

URI returns request URI.

func (*Request) URIWithErr

func (req *Request) URIWithErr() (u *URI, err error)

URIWithErr URI returns request URI.

func (*Request) Write

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

Write writes request to w.

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

Send MultipartForm only when Request.Body is empty. Priority of Request Body(Mutually Exclusive): bodyStream > Request.Body > MultipartForm > PostArgs

See also WriteTo.

func (*Request) WriteTimeout

func (req *Request) WriteTimeout() time.Duration

func (*Request) WriteTo

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

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

type RequestConfig

type RequestConfig struct {
	// It has the same meaning as the `Server.ReadTimeout` field value,
	// but it is applicable to a single connection.
	// Additionally, the timeout set only applies to reading the request body.
	// Zero and negative values will be ignored.
	ReadTimeout time.Duration
	// It has the same meaning as the Server.WriteTimeout field value,
	// but it is applicable to a single connection.
	// Additionally, the timeout set only applies to reading the request body.
	// Zero and negative values will be ignored.
	WriteTimeout time.Duration
	// It has the same meaning as the `Server.MaxRequestBodySize` field value,
	// but it is applicable to a single connection.
	MaxRequestBodySize int64
}

RequestConfig configure the per request deadline and body limits.

type RequestCtx

type RequestCtx struct {

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

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

RequestCtx contains incoming request and manages outgoing response.

It is forbidden copying RequestCtx instances.

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

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

func (*RequestCtx) 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) (fh *multipart.FileHeader, err 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) (v []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,

Example
package main

import (
	"fmt"
	"log"
	"net"

	"github.com/valyala/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) HijackConn

func (ctx *RequestCtx) HijackConn()

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 sent 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) ID

func (ctx *RequestCtx) ID() uint64

ID returns unique ID of the request.

func (*RequestCtx) IfModifiedSince

func (ctx *RequestCtx) IfModifiedSince(lastModified time.Time) (modified 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*. Is the `Response.bodyStream` field set?

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() (ok 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) 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/valyala/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 request body.

The returned bytes are valid until your request handler returns. The request body, including the request body represented in any form.

If the request body is represented as a stream and an error is encountered while reading, an error message string will be returned as the value.

func (*RequestCtx) QueryArgs

func (ctx *RequestCtx) QueryArgs() *Args

QueryArgs returns query arguments from RequestURI.

It doesn't return Posted 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.

After this function returns, it does not mean that the file has been completely sent; for large files, streaming is used to send the data.

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.

After this function returns, it does not mean that the file has been completely sent; for large files, streaming is used to send the data.

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

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.

When `bodySize` is set to `-1`, it indicates that the response will be sent using Chunked encoding. Other negative values will result in setting the `Connection: close` header. 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`).

The response body sent in this manner is always transmitted using Chunked encoding.

Example
package main

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

	"github.com/valyala/fasthttp"
)

func main() {
	// Start fasthttp server for streaming responses.
	if err := fasthttp.ListenAndServe(":8080", responseStreamHandler); err != nil {
		log.Fatalf("unexpected error in server: %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) SetResponseWriter

func (ctx *RequestCtx) SetResponseWriter(rw func(w WriterFlusherCloser) error)

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) 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(ctx *RequestCtx)

RequestHandler must process incoming requests.

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

func CompressHandler

func CompressHandler(h RequestHandler) RequestHandler

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

func CompressHandlerLevel

func CompressHandlerLevel(h RequestHandler, cfg CompressConfig) RequestHandler

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/valyala/fasthttp"
)

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

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

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

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

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

type RequestHandlerWithError

type RequestHandlerWithError func(ctx *RequestCtx) (err error)

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

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

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() int64

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

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

DelCanonical deletes header with the given key assuming key is canonical form.

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

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

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

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

Host returns Host header value.

func (*RequestHeader) IsConnect

func (h *RequestHeader) IsConnect() bool

IsConnect returns true if request method is CONNECT.

func (*RequestHeader) IsDelete

func (h *RequestHeader) IsDelete() bool

IsDelete returns true if request method is DELETE.

func (*RequestHeader) IsGet

func (h *RequestHeader) IsGet() bool

IsGet returns true if request method is GET.

func (*RequestHeader) IsHTTP11

func (h *RequestHeader) IsHTTP11() bool

IsHTTP11 returns true if the request is HTTP/1.1.

func (*RequestHeader) IsHead

func (h *RequestHeader) IsHead() bool

IsHead returns true if request method is HEAD.

func (*RequestHeader) IsOptions

func (h *RequestHeader) IsOptions() bool

IsOptions returns true if request method is OPTIONS.

func (*RequestHeader) IsPatch

func (h *RequestHeader) IsPatch() bool

IsPatch returns true if request method is PATCH.

func (*RequestHeader) IsPost

func (h *RequestHeader) IsPost() bool

IsPost returns true if request method is POST.

func (*RequestHeader) IsPut

func (h *RequestHeader) IsPut() bool

IsPut returns true if request method is PUT.

func (*RequestHeader) IsTrace

func (h *RequestHeader) IsTrace() bool

IsTrace returns true if request method is TRACE.

func (*RequestHeader) Len

func (h *RequestHeader) Len() int

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

func (*RequestHeader) Method

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

Method returns HTTP request method.

func (*RequestHeader) MultipartFormBoundary

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

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

func (*RequestHeader) Peek

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

Peek returns header value for the given key.

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

func (*RequestHeader) 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) PeekAllBytes

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

func (*RequestHeader) PeekAllCanonical

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

PeekAllCanonical Same as PeekAll assuming that key is in canonical form.

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

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

PeekCanonical returns header value for the given key assuming that key is in canonical form.

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

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

func (*RequestHeader) PeekCanonicalNoSpecialStr

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

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) (err 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) Reset

func (h *RequestHeader) Reset()

Reset clears request header.

func (*RequestHeader) ResetConnectionClose

func (h *RequestHeader) ResetConnectionClose()

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

func (*RequestHeader) Set

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

Set sets the given 'key: value' header.

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

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

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

func (*RequestHeader) SetCanonicalNoSpecial

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

func (*RequestHeader) SetCanonicalNoSpecialK

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

func (*RequestHeader) SetCanonicalNoSpecialKV

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

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

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

func (h *RequestHeader) SetCookieBytes(value []byte)

SetCookieBytes Directly adding a new cookie through the cookie string will not overwrite the already added 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) SetDate

func (h *RequestHeader) SetDate(value []byte)

SetDate no op method. Date head is managed automatically. This method is provided because we can't always remember which headers are handled automatically.

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

func (h *RequestHeader) SetTransferEncoding(value []byte)

SetTransferEncoding is no op Transfer-Encoding is managed automatically. This method is provided because we can't always remember which headers are handled automatically.

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

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

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.

func (*RequestHeader) Write

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

Write writes request header to w.

func (*RequestHeader) WriteTo

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

WriteTo writes request header to w.

WriteTo implements io.WriterTo interface.

type Resolver

type Resolver interface {
	LookupIPAddr(context.Context, string) (names []net.IPAddr, err error)
}

Resolver represents interface of the tcp resolver.

type ResourceLimitType

type ResourceLimitType int

ResourceLimitType Used to represent the type of server resource limitation. Currently, it includes two types: the maximum number of simultaneous connections the server can handle and the maximum number of connections that can be maintained simultaneously per IP.

const (
	// MaxConCurrencyLimit The server's current number of connections has exceeded the value
	// specified by the `Server.Concurrency` field.
	MaxConCurrencyLimit ResourceLimitType = iota
	// MaxConPerIpLimit The number of simultaneous connections opened by a single IP address has
	// exceeded the value specified by the `Server.MaxConnsPerIP` field.
	MaxConPerIpLimit
)

type Response

type Response struct {

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

	// Used for the server.
	// After writing the response headers to the `bw` buffer, is `Flush` executed immediately?
	ImmediateHeaderFlush bool

	// Used only for the client.
	// Whether to read the response body as a 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.
	//
	// For the server, if the request method is `HEAD`, this field will be set to `true`
	// in the `Server.serveConn` method.
	// For the client, if the request is a `HEAD` method, this field will automatically be set to `true`.
	// In transport.RoundTrip method.
	SkipBody bool
	// contains filtered or unexported fields
}

Response represents HTTP response.

In the client, it represents the content of the response corresponding to the request. In the server, it represents the content of the response to the request.

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

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

AppendBody appends p to response body.

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

func (*Response) AppendBodyString

func (resp *Response) AppendBodyString(s string)

AppendBodyString appends s to response body.

func (*Response) Body

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

Body returns response body.

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

Return the request body in the following order: `bodyStream`, `bodyRaw`, `body` field. The returned body is a reference and remains valid until the body in the `resp` is modified. If an error occurs while closing the body stream, the error is returned as the content of the body.

The `bodyStream` will always be closed, so it is recommended to handle `bodyStream` separately. it may result in a memory overflow.

Each time the result is the same, it will be cached in the `body` field.

func (*Response) BodyGunzip

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

BodyGunzip returns un-gzipped body data.

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

The `body` content will always be decompressed, regardless of the `Content-Encoding`.

func (*Response) BodyInflate

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

BodyInflate returns inflated body data.

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

func (*Response) BodyStream

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

BodyStream returns io.Reader.

You must CloseBodyStream or ReleaseResponse after you use it.

func (*Response) BodyUnbrotli

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

BodyUnbrotli returns un-brotlied body data.

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

The `body` content will always be decompressed, regardless of the `Content-Encoding`.

func (*Response) BodyUncompressed

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

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

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

BodyUnzstd The body content will always be decompressed, regardless of the Content-Encoding.

func (*Response) BodyWithError

func (resp *Response) BodyWithError() (data []byte, err error)

BodyWithError Return the request body in the following order: `bodyStream`, `bodyRaw`, `body` field. The returned body is a reference and remains valid until the body in the `resp` is modified. If an error occurs while closing the body stream

The `bodyStream` will always be closed, so it is recommended to handle `bodyStream` separately. it may result in a memory overflow.

Each time the result is the same, it will be cached in the `body` field.

func (*Response) BodyWriteTo

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

BodyWriteTo writes response body to w.

func (*Response) BodyWriter

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

BodyWriter returns writer for populating response body.

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

func (*Response) CloseBodyStream

func (resp *Response) CloseBodyStream() error

func (*Response) CompressPool

func (resp *Response) CompressPool() compress.Pooler

func (*Response) ConnectionClose

func (resp *Response) ConnectionClose() bool

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

func (*Response) CopyTo

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

CopyTo copies resp contents to dst except of body stream and chunkedW.

func (*Response) IsBodyStream

func (resp *Response) IsBodyStream() bool

IsBodyStream returns true if body is set via SetBodyStream*.

func (*Response) KeepBuffer

func (resp *Response) KeepBuffer() bool

func (*Response) LocalAddr

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

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

func (*Response) Read

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

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

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

func (*Response) ReadBody

func (resp *Response) ReadBody(r *bufio.Reader, maxBodySize int64) (err error)

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

func (resp *Response) ReadBodyStream(r *bufio.Reader, maxBodySize int64) (err error)

func (*Response) ReadLimit

func (resp *Response) ReadLimit(r *bufio.Reader, maxBodySize int64) (err error)

ReadLimit 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) ReadLimitIfClose

func (resp *Response) ReadLimitIfClose(r *bufio.Reader, maxBodySize int64) (closeConn bool, err error)

ReadLimitIfClose If the response does not have a Content-Length header and the response body should not be skipped, the connection should be closed after the response has been fully read.

This is because such a response requires waiting for the peer to close the connection in order to complete reading the response. However, the `io.EOF` triggered by the peer closing the connection cannot be observed in this context.

func (*Response) ReleaseBody

func (resp *Response) ReleaseBody(size int)

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

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

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

func (*Response) RemoteAddr

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

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

func (*Response) Reset

func (resp *Response) Reset()

Reset clears response contents. Except keepBuffer field unchanged.

func (*Response) ResetBody

func (resp *Response) ResetBody()

ResetBody resets response body.

func (*Response) SendFile

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

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

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

func (*Response) SetBody

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

SetBody sets response body.

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

func (*Response) SetBodyRaw

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

SetBodyRaw sets response body, but without copying it.

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

func (*Response) SetBodyStream

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

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

func (resp *Response) SetBodyStreamChunkedWriter(sw StreamChunkedWriter)

SetBodyStreamChunkedWriter We will use chunked encoding no matter what.

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

func (resp *Response) SetBodyString(body string)

SetBodyString sets response body.

func (*Response) SetCompressPool

func (resp *Response) SetCompressPool(compressPool compress.Pooler)

func (*Response) SetConnectionClose

func (resp *Response) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*Response) SetKeepBuffer

func (resp *Response) SetKeepBuffer(keep bool)

SetKeepBuffer Whether to return the storage slices to the cache pool when the Response object is reset

func (*Response) SetStatusCode

func (resp *Response) SetStatusCode(statusCode int)

SetStatusCode sets response status code.

func (*Response) StatusCode

func (resp *Response) StatusCode() int

StatusCode returns response status code.

func (*Response) String

func (resp *Response) String() string

String returns response representation.

Returns error message instead of response representation on error.

Use Write instead of String for performance-critical code.

func (*Response) SwapBody

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

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

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

The `bodyStream` will always be closed, and if an error occurs during the closing, the error will be returned as the value.

The parameter `body` will exist as the underlying slice of the `body`. The return value is not a reference, and the parameter `body` cannot be used by the caller anymore.

func (*Response) Write

func (resp *Response) Write(w *bufio.Writer) (err error)

Write writes response to w.

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

See also WriteTo. w.Flush method don't be called by this method.

func (*Response) WriteChunkedStream

func (resp *Response) WriteChunkedStream(w *bufio.Writer) (err error)

WriteChunkedStream We will use chunked encoding no matter what.

func (*Response) WriteCompress

func (resp *Response) WriteCompress(w *bufio.Writer) (err error)

func (*Response) WriteDeflate

func (resp *Response) WriteDeflate(w *bufio.Writer) error

WriteDeflate writes response with deflated body to w.

The method deflates response body and sets 'Content-Encoding: deflate' header before writing response to w.

WriteDeflate doesn't flush response to w for performance reasons.

func (*Response) WriteDeflateLevel

func (resp *Response) WriteDeflateLevel(w *bufio.Writer, level int) error

WriteDeflateLevel writes response with deflated body to w.

Level is the desired compression level:

  • CompressNoCompression
  • CompressBestSpeed
  • CompressBestCompression
  • CompressDefaultCompression
  • 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

func (resp *Response) WriteGzip(w *bufio.Writer) error

WriteGzip writes response with gzipped body to w.

The method WriteGzip 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

func (resp *Response) WriteGzipLevel(w *bufio.Writer, level int) error

WriteGzipLevel writes response with gzipped body to w.

Level is the desired compression level:

  • CompressNoCompression
  • CompressBestSpeed
  • CompressBestCompression
  • CompressDefaultCompression
  • 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.

func (*Response) WriteHeader

func (resp *Response) WriteHeader(w *bufio.Writer) (err error)

func (*Response) WriteTo

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

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

type ResponseHeader

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

ResponseHeader represents HTTP response header.

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

ResponseHeader instance MUST NOT be used from concurrently running goroutines.

func (*ResponseHeader) Add

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

Add adds the given 'key: value' header.

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

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

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

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

AddCanonical Same as Add assuming key is canonical form.

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, compressed ...bool) []byte

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

func (*ResponseHeader) AppendBytesNoCRLFEncodingLength

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

func (*ResponseHeader) Charset

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

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() int64

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

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

DelCanonical deletes header with the given key assuming key is canonical form.

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

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

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(compressed ...bool) []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.

When the `compress` parameter is passed, neither the `Content-Length` header nor the delimiter between the headers and the response body will be written.

func (*ResponseHeader) HeaderNoCRLFEncodingLength

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

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

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

PeeKCanonical returns header value for the given key assuming that key is in canonical form.

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

func (*ResponseHeader) PeeKCanonicalK

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

func (*ResponseHeader) Peek

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

Peek returns header value for the given key assuming that key is in canonical form.

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

func (*ResponseHeader) PeekAll

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

PeekAll returns all header value for the given key.

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

func (*ResponseHeader) PeekAllBytes

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

func (*ResponseHeader) PeekAllCanonical

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

PeekAllCanonical Same as PeekAll assuming that key is in canonical form.

func (*ResponseHeader) PeekBytes

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

PeekBytes returns header value for the given key.

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

func (*ResponseHeader) PeekCanonicalNoSpecial

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

func (*ResponseHeader) PeekCanonicalNoSpecialK

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

func (*ResponseHeader) PeekCookie

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

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

func (*ResponseHeader) PeekKeys

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

PeekKeys return all header keys.

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

func (*ResponseHeader) PeekTrailerKeys

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

PeekTrailerKeys return all trailer keys.

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

func (*ResponseHeader) Protocol

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

Protocol returns response protocol bytes.

func (*ResponseHeader) Read

func (h *ResponseHeader) Read(r *bufio.Reader) (err error)

Read reads response header from r.

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

func (*ResponseHeader) ReadTrailer

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

ReadTrailer reads response trailer header from r.

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

func (*ResponseHeader) Reset

func (h *ResponseHeader) Reset()

Reset clears response header.

func (*ResponseHeader) ResetConnectionClose

func (h *ResponseHeader) ResetConnectionClose()

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

func (*ResponseHeader) Server

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

Server returns Server header value.

func (*ResponseHeader) Set

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

Set sets the given 'key: value' header.

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

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

func (*ResponseHeader) SetBytesK

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

SetBytesK sets the given 'key: value' header.

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

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

func (*ResponseHeader) SetBytesKV

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

SetBytesKV sets the given 'key: value' header.

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

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

func (*ResponseHeader) SetBytesV

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

SetBytesV sets the given 'key: value' header.

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

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

func (*ResponseHeader) SetCanonical

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

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

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

func (*ResponseHeader) SetConnectionClose

func (h *ResponseHeader) SetConnectionClose()

SetConnectionClose sets 'Connection: close' header.

func (*ResponseHeader) SetContentEncoding

func (h *ResponseHeader) SetContentEncoding(contentEncoding string)

SetContentEncoding sets Content-Encoding header value.

func (*ResponseHeader) SetContentEncodingBytes

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

SetContentEncodingBytes sets Content-Encoding header value.

func (*ResponseHeader) SetContentLength

func (h *ResponseHeader) SetContentLength(contentLength int64)

SetContentLength sets Content-Length header value.

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

func (*ResponseHeader) SetContentRange

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

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

func (*ResponseHeader) SetContentType

func (h *ResponseHeader) SetContentType(contentType string)

SetContentType sets Content-Type header value.

func (*ResponseHeader) SetContentTypeBytes

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

SetContentTypeBytes sets Content-Type header value.

func (*ResponseHeader) SetCookie

func (h *ResponseHeader) SetCookie(cookie *Cookie)

SetCookie sets the given response cookie.

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

func (*ResponseHeader) SetCookieBytes

func (h *ResponseHeader) SetCookieBytes(value []byte)

func (*ResponseHeader) SetCookieBytesK

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

SetCookieBytesK sets 'key: value' cookies.

func (*ResponseHeader) SetCookieBytesKV

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

SetCookieBytesKV sets 'key: value' cookies.

func (*ResponseHeader) SetCookieString

func (h *ResponseHeader) SetCookieString(key, value string)

SetCookieString sets 'key: value' cookies.

func (*ResponseHeader) SetDate

func (h *ResponseHeader) SetDate(value []byte)

SetDate no op method. Date head is managed automatically. This method is provided because we can't always remember which headers are handled automatically.

func (*ResponseHeader) SetLastModified

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

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

func (*ResponseHeader) SetNoDefaultContentType

func (h *ResponseHeader) SetNoDefaultContentType(noDefaultContentType bool)

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

func (*ResponseHeader) SetProtocol

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

SetProtocol sets response protocol bytes.

func (*ResponseHeader) SetServer

func (h *ResponseHeader) SetServer(server string)

SetServer sets Server header value.

func (*ResponseHeader) SetServerBytes

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

SetServerBytes sets Server header value.

func (*ResponseHeader) SetStatusCode

func (h *ResponseHeader) SetStatusCode(statusCode int)

SetStatusCode sets response status code.

func (*ResponseHeader) SetStatusMessage

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

SetStatusMessage sets response status message bytes.

func (*ResponseHeader) SetTrailer

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

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

Use Set to set the trailer header later.

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

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

Return ErrBadTrailer if contain any forbidden trailers.

func (*ResponseHeader) SetTrailerBytes

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

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

Use Set to set the trailer header later.

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

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

Return ErrBadTrailer if contain any forbidden trailers.

func (*ResponseHeader) SetTransferEncoding

func (h *ResponseHeader) SetTransferEncoding(value []byte)

SetTransferEncoding is no op Transfer-Encoding is managed automatically. This method is provided because we can't always remember which headers are handled automatically.

func (*ResponseHeader) StatusCode

func (h *ResponseHeader) StatusCode() int

StatusCode returns response status code.

func (*ResponseHeader) StatusMessage

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

StatusMessage returns response status message.

func (*ResponseHeader) String

func (h *ResponseHeader) String() string

String returns response header representation.

func (*ResponseHeader) TrailerHeader

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

TrailerHeader returns response trailer header representation.

Trailers will only be received with chunked transfer.

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

func (*ResponseHeader) VisitAll

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

VisitAll calls f for each header.

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

func (*ResponseHeader) VisitAllCookie

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

VisitAllCookie calls f for each response cookie.

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

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

func (*ResponseHeader) VisitAllTrailer

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

VisitAllTrailer calls f for each response Trailer.

f must not retain references to value after returning.

func (*ResponseHeader) Write

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

Write writes response header to w.

func (*ResponseHeader) WriteCompress

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

WriteCompress writes response header to w. Neither the Content-Length header nor the delimiter between the headers and the response body will be written.

func (*ResponseHeader) WriteNoCRLFEncodingLength

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

func (*ResponseHeader) WriteTo

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

WriteTo writes response header to w.

WriteTo implements io.WriterTo interface.

type ResponseStreamWriter

type ResponseStreamWriter struct {
	// The response is cached here first. It is written to `cw` when
	// the cache is full or when a flush occurs.
	WriterFlusher
	// contains filtered or unexported fields
}

ResponseStreamWriter Send the response in Chunked encoding format.

func (ResponseStreamWriter) Close

func (r ResponseStreamWriter) Close() (err error)

Close the `WriterFlusher` to release resources or flush the contents in the `WriterFlusher`. Here, the contents of `cw` are not flushed. Delay sending the chunked encoding's final chunk and the trailers headers until the end.

In the `Close` method, we do not flush the contents of `bw` because there are still Chunked encoding's trailing content and possibly trailers headers that need to be written.

func (ResponseStreamWriter) Flush

func (r ResponseStreamWriter) Flush() (err error)

Flush the cached response to `cw`, which encodes it as Chunked. Then flush the contents of `cw` to the `net.Conn`.

type RetryIfErrFunc

type RetryIfErrFunc func(request *Request, retryCount int, err error) (sleepDuration time.Duration, resetReqTime bool, retry bool)

RetryIfErrFunc defines an interface used for implementing the following functionality: When the client encounters an error during a request, the behavior—whether to retry, whether to retry later, or whether to reset the request timeout—should be determined based on the return value of this interface.

retryCount indicates which retry attempt this is, with retry counting starting from 1. The first request execution is not considered a retry. err represents the error encountered during the previous request. sleepDuration if is greater than 0, the retry will be executed after this interval. resetReqTime indicates whether to reset the request timeout to its initial value before executing this retry. retry indicates whether to perform this retry. If false, the request function will return immediately.

type RoundTripper

type RoundTripper interface {
	RoundTrip(hc *HostClient, req *Request, resp *Response) (retry bool, err error)
}

RoundTripper wraps every request/response.

var DefaultTransport RoundTripper = &transport{}

type SendFiler

type SendFiler interface {
	FileOrLimitedReader() io.Reader
}

type ServeHandler

type ServeHandler func(c net.Conn) error

ServeHandler must process tls.Config.NextProto negotiated requests.

type Server

type Server struct {

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

	// ErrorHandler for Errors encountered while receiving requests, parsing requests, and sending responses
	// may sometimes make it impossible to determine the connection status or the
	// state of data consumption.
	//
	// The following is a non-exhaustive list of errors that can be expected as argument:
	//
	//   * io.ErrUnexpectedEOF
	//   * ErrGetOnly
	//   * HeaderBufferSmallErr
	//   * ErrUnexpectedReqBodyEOF
	//   * ErrUnexpectedRespBodyEOF
	//   * ErrBodyTooLarge
	//   * ErrBrokenChunk
	//   * HeaderParseErr
	// There are also some network errors such as timeouts, connection resets, and unexpected disconnections.
	ErrorHandler func(ctx *RequestCtx, err error)

	// HeaderReceived is called after receiving the header.
	//
	// Non-zero RequestConfig field values will overwrite the default configs
	// This function is called after reading the request headers and before reading the request body.
	HeaderReceived func(header *RequestHeader) RequestConfig

	// ContinueHandler is called after receiving the Expect 100 Continue Header.
	//
	// https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3
	// https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.1
	// Using ContinueHandler a server can make decisioning on whether
	// to read a potentially large request body based on the headers.
	//
	// If this field is not set or its value returns true after being called,
	// a 100 Continue response will be automatically sent upon receiving an
	// Expect 100 Continue request, and then it will block while waiting
	// for the request body to arrive.
	//
	// If return false sending  417 Expectation Failed and close connection.
	ContinueHandler func(header *RequestHeader) bool

	// Server name for sending in response headers. default value is fasthttp
	//
	// The Server header is determined by the following priority:
	// the value set in RequestHeader, the value of this field, and the global default value.
	Name string

	// The maximum number of concurrent connections the server may serve.
	// Does not include links that have already been hijacked
	//
	// DefaultConcurrency is used if not set. Default value is  256 * 1024.
	//
	// Concurrency only works if you either call Serve once, or only ServeConn multiple times.
	// It works with ListenAndServe as well.
	// A zero or negative value indicates the default value.
	Concurrency int

	// Per-connection buffer size for requests' reading.
	// This also limits the maximum header size.
	//
	// Default buffer size is used if not set. Default value is 4096.
	//
	// Since the `readRawHeaders` function first reads the entire request header into the
	// `RequestHeader.rawHeaders` field before parsing it line by line, this reading
	// process initially buffers the entire header into the `bufio.Reader`'s buffer.
	// The size of this buffer is determined by the `ReadBufferSize` field.
	//
	// If the value exceeds this field, the server will send a 413 response.
	// 431 Request Header Fields Too Large.
	// A zero or negative value indicates the default value.
	ReadBufferSize int

	// Per-connection buffer size for responses' writing.
	//
	// Default buffer size is used if not set. Default value is 4096.
	//
	// The response is typically buffered up to the size specified by the `WriteBufferSize`.
	// It is only when the buffer is full or a flush is triggered that the data is sent to
	// the underlying connection.
	//
	// It does not affect the correctness of the program. A larger buffer can reduce the number of system calls.
	// A zero or negative value indicates the default value.
	WriteBufferSize int

	// ReadTimeout is the amount of time allowed to read
	// the full request's Header and Body.
	//
	// If the `HeaderReceived` field is also set with `ReadTimeout`, this field will only
	// apply to the reading of the request headers.
	//
	// By default, request read timeout is unlimited.
	//
	// When a connection is set to be hijacked, any timeouts related to the hijacking will be reset
	// after RequestHandler return.
	// A zero or negative value indicates no limit.
	ReadTimeout time.Duration

	// WriteTimeout The timeout for the completion of the response begins counting from the moment
	// the `RequestHandler` returns.
	//
	// By default, response write timeout is unlimited.
	// When a connection is set to be hijacked, any timeouts related to the hijacking will be reset
	// after RequestHandler return.
	// A zero or negative value indicates no limit.
	WriteTimeout time.Duration

	// IdleTimeout The timeout starts immediately after the previous request is completed and
	// continues until the first byte of the next request is read.
	// This field is only effective when the `TCPKeepalive` field is set to `true`.
	// A zero or negative value indicates no limit.
	IdleTimeout time.Duration

	// Maximum number of concurrent client connections allowed per IP.
	//
	// By default, unlimited number.
	// A zero or negative value indicates no limit.
	MaxConnsPerIP int
	// MaxIdleWorkerDuration is the maximum idle time of a single worker in the underlying
	// worker pool of the Server. Idle workers beyond this time will be cleared.
	// The resources associated with it are just a channel and a goroutine.
	// An idle worker means a worker that does not have any connections currently being served.
	MaxIdleWorkerDuration time.Duration

	// The return value of this field determines how many of the idle workers in the list will be removed.
	CleanThreshold CleanThresholdFunc

	// TCPKeepalivePeriod is the duration the connection needs to
	// remain idle before TCP starts sending keepalive probes.
	//
	// This field is only effective when TCPKeepalive is set to true.
	// A zero value indicates that the operating system's default setting will be used.
	TCPKeepalivePeriod time.Duration

	// Maximum request body size.
	// The size does not include the request headers.
	// If the value exceeds this field, the server will send a 431 response
	// and close connection.
	// Request body size is limited by DefaultMaxRequestBodySize(4MB) by default.
	// A zero or negative value indicates the default value.
	MaxRequestBodySize int64

	// Determines whether a connection can only serve a single request.
	// If this field is set to `true`, it will send `Connection: close` and
	// close the connection after sending the response.
	DisableKeepalive bool

	// Whether the operating system should send tcp keep-alive messages on the tcp connection.
	//
	// By default, tcp keep-alive connections are disabled.
	//
	// This option is used only if default TCP dialer is used,
	// i.e. if Dial and DialTimeout are blank.
	TCPKeepalive bool

	// Aggressively reduces memory usage at the cost of higher CPU usage
	// if set to true.
	//
	// Try enabling this option only if the server consumes too much memory
	// serving mostly idle keep-alive connections. This may reduce memory
	// usage by more than 50%.
	//
	// Aggressive memory usage reduction is disabled by default.
	//
	// Release the read buffer immediately after completing request reading,
	// and release the write buffer after completing response writing.
	// Release the `RequestCtx` before reading the first byte of the next request.
	ReduceMemoryUsage bool

	// Rejects all non-GET requests if set to true.
	//
	// This option is useful as anti-DoS protection for servers
	// accepting only GET requests and HEAD requests.
	//
	// Server accepts all the requests by default.
	GetOnly bool

	// Will not pre parse Multipart Form data if set to true.
	//
	// This option is useful for servers that desire to treat
	// multipart form data as a binary blob, or choose when to parse the data.
	//
	// Server pre parses multipart form data by default.
	DisablePreParseMultipartForm bool

	// Logs all errors, including the most frequent
	// 'connection reset by peer', 'broken pipe' and 'connection timeout'
	// errors. Such errors are common in production serving real-world
	// clients.
	//
	// By default, the most frequent errors such as
	// 'connection reset by peer', 'broken pipe' and 'connection timeout'
	// are suppressed in order to limit output log traffic.
	LogAllErrors bool

	// Will not log potentially sensitive content in error logs
	//
	// This option is useful for servers that handle sensitive data
	// in the request/response.
	//
	// Server logs all full errors by default.
	// Deprecated
	SecureErrorLogMessage bool

	// Regardless of how this field is set, the header names are always
	// formatted during HTTP header parsing.
	// This field only affects the response headers.
	//
	// Header names are passed as-is without normalization
	// if this option is set.
	//
	// Disabled header names' normalization may be useful only for proxying
	// incoming requests to other servers expecting case-sensitive
	// header names. See https://github.com/valyala/fasthttp/issues/57
	// for details.
	//
	// By default, request and response header names are normalized, i.e.
	// The first letter and the first letters following dashes
	// are uppercased, while all the other letters are lowercased.
	// Examples:
	//
	//     * HOST -> Host
	//     * content-type -> Content-Type
	//     * cONTENT-lenGTH -> Content-Length
	//
	// In the `Server.serveConn` method, set the `RequestHeader.
	// disableNormalizing` and `ResponseHeader.disableNormalizing` fields
	// each time a new request arrives.
	DisableHeaderNamesNormalizing bool

	// SleepWhenConcurrencyLimitsExceeded is a duration to be slept of if
	// the concurrency limit in exceeded (default [when is 0]: don't sleep
	// and accept new connections immediately).
	//
	// This field mainly prevents the scenario where, due to concurrent
	// connections exceeding the limit, new connections are immediately
	// closed because they cannot be serviced even if they start to be received.
	SleepWhenConcurrencyLimitsExceeded time.Duration

	// NoDefaultServerHeader, when set to true, causes the default Server header
	// to be excluded from the Response, When the `ResponseHeader` does not have
	// the `Server` header set and the `Name` field is also not set.
	NoDefaultServerHeader bool

	// NoDefaultDate, when set to true, causes the default Date
	// header to be excluded from the Response.
	//
	// The default Date header value is the current date value. When
	// set to true, the Date will not be present.
	//
	// For optimization purposes, internal time is cached, so even
	// if the response sets its own `Date` header, it will be ignored.
	NoDefaultDate bool

	// NoDefaultContentType, When the `Content-Type` header is not set
	// in the `ResponseHeader`, should the default value be used or not?
	// Default value is text/plain; charset=utf-8
	NoDefaultContentType bool

	// KeepHijackedConns After a connection is hijacked,
	// should the lifecycle of the connection continue to be managed by Server?
	KeepHijackedConns bool

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

	// StreamRequestBody enables request body streaming,
	// Unless it is Chunked encoding, a portion of the request body will still
	// be pre-read before calling the handler.
	//
	// When `StreamRequestBody` is set to `true`, the size of the request body
	// is not limited by the `MaxRequestBodySize` field value.
	StreamRequestBody bool
	// When closing the request stream, is the unread content
	// read into `io.Discard` to avoid interfering with the reading of the next request?
	// In `net/http`, after the `Handler` returns, it always attempts to drain any unread request body.
	DiscardUnReadRequestBodyStream bool

	// ConnState specifies an optional callback function that is
	// called when a client connection changes state. See the
	// ConnState type and associated constants for details.
	//
	// StateNew StateClosed StateHijacked StateIdle StateActiveR
	// StateActiveW
	// Setting these statuses will all invoke this field's value.
	ConnState func(net.Conn, ConnState)

	// Logger, which is used by RequestCtx.Logger().
	//
	// By default standard logger from log package is used.
	Logger Logger

	// TLSConfig optionally provides a TLS configuration for use
	// by ServeTLS, ServeTLSEmbed, ListenAndServeTLS, ListenAndServeTLSEmbed,
	// AppendCert, AppendCertEmbed and NextProto.
	//
	// Note that this value is cloned by ServeTLS, ServeTLSEmbed, ListenAndServeTLS
	// and ListenAndServeTLSEmbed, so it's not possible to modify the configuration
	// with methods like tls.Config.SetSessionTicketKeys.
	// To use SetSessionTicketKeys, use Server.Serve with a custom TLS Listener
	// instead.
	TLSConfig *tls.Config
	// This field value will be invoked when the concurrency exceeds the
	// limit or the `perIPConnCounter` exceeds the limit.
	//
	// The returned string will be immediately written to the client as the response,
	// and it must include both the response headers and body. The connection will
	// be closed after the response is sent.
	//
	// If this field is omitted, a 503 status code will be sent for the `MaxConCurrencyLimit`
	// limit, and a 429 status code will be sent for the `MaxConPerIpLimit` limit. The response
	// body will contain the corresponding status information.
	ResourceLimitError func(lt ResourceLimitType) (body string)
	// contains filtered or unexported fields
}

Server implements HTTP server.

Default Server settings should satisfy the majority of Server users. Adjust Server settings only if you really understand the consequences.

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

It is safe to call Server methods from concurrently running goroutines.

Example
package main

import (
	"fmt"
	"log"

	"github.com/valyala/fasthttp"
)

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

	// Create custom server.
	s := &fasthttp.Server{
		Handler: requestHandler,

		// Every response will contain 'Server: My super server' header.
		Name: "My super server",

		// Other Server settings may be set here.
	}

	// Start the server listening for incoming requests on the given address.
	//
	// ListenAndServe returns only on error, so usually it blocks forever.
	if err := s.ListenAndServe("127.0.0.1:80"); err != nil {
		log.Fatalf("error in ListenAndServe: %v", err)
	}
}
Output:

func (*Server) AppendCert

func (s *Server) AppendCert(certFile, keyFile string) error

AppendCert appends certificate and keyfile to TLS Configuration.

This function allows programmer to handle multiple domains in one server structure. See examples/multidomain.

func (*Server) AppendCertEmbed

func (s *Server) AppendCertEmbed(certData, keyData []byte) error

AppendCertEmbed does the same as AppendCert but using in-memory data. Both `certData` and `keyData` must be provided and valid, otherwise `ErrCertAndKeyMustProvided` will be returned.

func (*Server) GetCurrentConcurrency

func (s *Server) GetCurrentConcurrency() uint32

GetCurrentConcurrency returns a number of currently served connections.

This function is intended be used by monitoring systems. This does not include connections that were rejected due to resource limitations.

func (*Server) GetOpenConnectionsCount

func (s *Server) GetOpenConnectionsCount() int32

GetOpenConnectionsCount returns a number of opened connections. This includes connections that were rejected due to resource limitations. This does not include the `net.Listener` count. This function is intended be used by monitoring systems.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(addr string) error

ListenAndServe serves HTTP requests from the given TCP4 addr.

Pass custom listener to Serve if you need listening on non-TCP4 media such as IPv6.

Accepted connections are configured to enable TCP keep-alive.

func (*Server) ListenAndServeTLS

func (s *Server) ListenAndServeTLS(addr, certFile, keyFile string) error

ListenAndServeTLS serves HTTPS requests from the given TCP4 addr.

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

Pass custom listener to Serve if you need listening on non-TCP4 media such as IPv6.

If the certFile or keyFile has not been provided to the server structure, the function will use the previously added TLS configuration.

Accepted connections are configured to enable TCP keep-alive.

func (*Server) ListenAndServeTLSEmbed

func (s *Server) ListenAndServeTLSEmbed(addr string, certData, keyData []byte) error

ListenAndServeTLSEmbed serves HTTPS requests from the given TCP4 addr.

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

Pass custom listener to Serve if you need listening on arbitrary media such as IPv6.

If the certFile or keyFile has not been provided the server structure, the function will use previously added TLS configuration.

Accepted connections are configured to enable TCP keep-alive.

func (*Server) ListenAndServeUNIX

func (s *Server) ListenAndServeUNIX(addr string, mode os.FileMode) error

ListenAndServeUNIX serves HTTP requests from the given UNIX addr.

The function deletes existing file at addr before starting serving.

The server sets the given file mode for the UNIX addr. Recommended mode is 0600.

func (*Server) ListenAndServeWithNotify

func (s *Server) ListenAndServeWithNotify(addr string, cancel context.CancelCauseFunc) error

func (*Server) NextProto

func (s *Server) NextProto(key string, nph ServeHandler)

NextProto adds nph to be processed when key is negotiated when TLS connection is established.

This function can only be called before the server is started.

func (*Server) RejectedByConcurrencyLimitCount

func (s *Server) RejectedByConcurrencyLimitCount() uint32

RejectedByConcurrencyLimitCount returns a number of rejected connections by Concurrency.

This function is intended be used by monitoring systems.

func (*Server) RejectedByPerIpLimitCount

func (s *Server) RejectedByPerIpLimitCount() uint32

RejectedByPerIpLimitCount returns a number of rejected connections by MaxConnsPerIP.

This function is intended be used by monitoring systems.

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

Serve serves incoming connections from the given listener.

Serve blocks until the given listener returns permanent error.

func (*Server) ServeConn

func (s *Server) ServeConn(c net.Conn) error

ServeConn serves HTTP requests from the given connection.

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

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

ServeConn closes c before returning.

func (*Server) ServeTLS

func (s *Server) ServeTLS(ln net.Listener, certFile, keyFile string) error

ServeTLS serves HTTPS requests from the given listener. If `Server.TLSConfig` is not configured, both `certFile` and `keyFile` must be non-empty. certFile and keyFile are paths to TLS certificate and key files.

If the certFile or keyFile has not been provided the server structure, the function will use previously added TLS configuration. After the server has started, changes to `Server.TLSConfig` will not take effect.

func (*Server) ServeTLSEmbed

func (s *Server) ServeTLSEmbed(ln net.Listener, certData, keyData []byte) error

ServeTLSEmbed serves HTTPS requests from the given listener.

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

If the certFile or keyFile has not been provided the server structure, the function will use previously added TLS configuration.

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners and then waiting indefinitely for all connections to return to idle and then shut down.

When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil. Make sure the program doesn't exit and waits instead for Shutdown to return.

To prevent the method from potentially blocking indefinitely due to dead connections, it is recommended to use it in conjunction with a timeout mechanism.

If a connection never enters the `StateIdle` state, this method will not return. If you want to return decisively after a certain period, refer to `ShutdownWithContext`.

func (*Server) ShutdownWithContext

func (s *Server) ShutdownWithContext(ctx context.Context) (err error)

ShutdownWithContext gracefully shuts down the server without interrupting any active connections. ShutdownWithContext works by first closing all open listeners and then waiting for all connections to return to idle or context timeout and then shut down.

When ShutdownWithContext is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil. Make sure the program doesn't exit and waits instead for Shutdown to return.

When `ctx` is canceled, this method will return immediately and will not wait for all active connections to be closed.

type StreamChunkedWriter

type StreamChunkedWriter func(w WriterFlusherCloser) error

type StreamWriter

type StreamWriter func(w *bufio.Writer)

StreamWriter must write data to w.

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

StreamWriter must return immediately if w returns error.

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

type TCPDialer

type TCPDialer struct {
	// Concurrency controls the maximum number of concurrent Dials
	// that can be performed using this object.
	// Setting this to 0 means unlimited.
	//
	// WARNING: This can only be changed before the first Dial.
	// Changes made after the first Dial will not affect anything.
	Concurrency int

	// LocalAddr is the local address to use when dialing an
	// address.
	// If nil, a local address is automatically chosen.
	LocalAddr *net.TCPAddr

	// This may be used to override DNS resolving policy, like this:
	// var dialer = &fasthttp.TCPDialer{
	// 	Resolver: &net.Resolver{
	// 		PreferGo:     true,
	// 		StrictErrors: false,
	// 		Dial: func (ctx context.Context, network, address string) (net.Conn, error) {
	// 			d := net.Dialer{}
	// 			return d.DialContext(ctx, "udp", "8.8.8.8:53")
	// 		},
	// 	},
	// }
	Resolver Resolver

	// DNSCacheDuration may be used to override the default DNS cache duration (DefaultDNSCacheDuration)
	DNSCacheDuration time.Duration

	// Period between tcp keep-alive messages.
	//
	// TCP keep-alive period is determined by operation system by default.
	TCPKeepalivePeriod time.Duration

	// DisableDNSResolution may be used to disable DNS resolution
	DisableDNSResolution bool
	// Whether to enable tcp keep-alive connections.
	//
	// Whether the operating system should send tcp keep-alive messages on the tcp connection.
	//
	// By default tcp keep-alive connections are disabled.
	TCPKeepalive bool
	// contains filtered or unexported fields
}

TCPDialer contains options to control a group of Dial calls.

func (*TCPDialer) Dial

func (d *TCPDialer) Dial(addr string) (net.Conn, error)

Dial dials the given TCP addr using tcp4.

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

  • It reduces load on DNS resolver by caching resolved TCP addressed for 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

** This function only uses IPv4 dialing with a default timeout of 3 seconds.

func (*TCPDialer) DialDualStack

func (d *TCPDialer) DialDualStack(addr string) (net.Conn, error)

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

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

  • It reduces load on DNS resolver by caching resolved TCP addressed for 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

** Dial using TCP with a default timeout of 3 seconds.

func (*TCPDialer) DialDualStackTimeout

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

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

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

  • It reduces load on DNS resolver by caching resolved TCP addressed for 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

** Dial using TCP with a specified timeout.

func (*TCPDialer) DialTimeout

func (d *TCPDialer) DialTimeout(network, addr string, timeout time.Duration) (conn net.Conn, err error)

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

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

  • It reduces load on DNS resolver by caching resolved TCP addressed for 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

** The network parameter only supports tcp and tcp4. A timeout parameter less than 0 ** means no timeout is used, while greater than 0 indicates the use of a default timeout of 3 seconds.

type TransportV2

type TransportV2 struct{}

type TwoBytesReader

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

func (*TwoBytesReader) Read

func (t *TwoBytesReader) Read(p []byte) (n int, err error)

type URI

type URI struct {

	// Path values are sent as-is without normalization.
	//
	// Disabled path normalization may be useful for proxying incoming requests
	// to servers that are expecting paths to be forwarded as-is.
	//
	// By default path values are normalized, i.e.
	// extra slashes are removed, special characters are encoded.
	DisablePathNormalizing bool
	// contains filtered or unexported fields
}

URI represents URI :) .

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

URI instance MUST NOT be used from concurrently running goroutines.

func AcquireURI

func AcquireURI() *URI

AcquireURI returns an empty URI instance from the pool.

Release the URI with ReleaseURI after the URI is no longer needed. This allows reducing GC load.

func (*URI) AppendBytes

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

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

func (*URI) CopyTo

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

CopyTo copies uri contents to dst.

func (*URI) FullURI

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

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

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

func (*URI) Hash

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

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

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

func (*URI) Host

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

Host returns host part, i.e. aaa.com of http://aaa.com/foo/bar?baz=123#qwe .

Host is always lowercased.

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

func (*URI) Hostname

func (u *URI) Hostname() string

Hostname returns u.Host, stripping any valid port number if present.

If the result is enclosed in square brackets, as literal IPv6 addresses are, the square brackets are removed from the result.

func (*URI) LastPathSegment

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

LastPathSegment returns the last part of uri path after '/'.

Examples:

  • For /foo/bar/baz.html path returns baz.html.
  • For /foo/bar/ returns empty byte slice.
  • For /foobar.js returns foobar.js.

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

func (*URI) Parse

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

Parse initializes URI from the given host and uri.

host may be nil. In this case uri must contain fully qualified uri, i.e. with scheme and host. http is assumed if scheme is omitted.

uri may contain e.g. RequestURI without scheme and host if host is non-empty.

func (*URI) Password

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

Password returns URI password.

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

func (*URI) Path

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

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

The returned path is always urldecoded and normalized, i.e. '//f%20obar/baz/../zzz' becomes '/f obar/zzz'.

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

func (*URI) PathOriginal

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

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

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

func (*URI) Port

func (u *URI) Port() string

Port returns the port part of u.Host, without the leading colon.

If u.Host doesn't contain a valid numeric port, Port returns an empty string.

func (*URI) QueryArgs

func (u *URI) QueryArgs() *Args

QueryArgs returns query args.

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

func (*URI) QueryString

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

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

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

func (*URI) RequestURI

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

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

func (*URI) Reset

func (u *URI) Reset()

Reset clears uri.

func (*URI) Scheme

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

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

Returned scheme is always lowercased.

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

func (*URI) SetHash

func (u *URI) SetHash(hash string)

SetHash sets URI hash.

func (*URI) SetHashBytes

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

SetHashBytes sets URI hash.

func (*URI) SetHost

func (u *URI) SetHost(host string)

SetHost sets host for the uri.

func (*URI) SetHostBytes

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

SetHostBytes sets host for the uri.

func (*URI) SetPassword

func (u *URI) SetPassword(password string)

SetPassword sets URI password.

func (*URI) SetPasswordBytes

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

SetPasswordBytes sets URI password.

func (*URI) SetPath

func (u *URI) SetPath(path string)

SetPath sets URI path.

func (*URI) SetPathBytes

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

SetPathBytes sets URI path.

func (*URI) SetQueryString

func (u *URI) SetQueryString(queryString string)

SetQueryString sets URI query string.

func (*URI) SetQueryStringBytes

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

SetQueryStringBytes sets URI query string.

func (*URI) SetScheme

func (u *URI) SetScheme(scheme string)

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

func (*URI) SetSchemeBytes

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

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

func (*URI) SetUsername

func (u *URI) SetUsername(username string)

SetUsername sets URI username.

func (*URI) SetUsernameBytes

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

SetUsernameBytes sets URI username.

func (*URI) String

func (u *URI) String() string

String returns full uri.

func (*URI) Update

func (u *URI) Update(newURI string)

Update updates uri.

The following newURI types are accepted:

  • Absolute, i.e. http://foobar.com/aaa/bb?cc . In this case the original uri is replaced by newURI.
  • Absolute without scheme, i.e. //foobar.com/aaa/bb?cc. In this case the original scheme is preserved.
  • Missing host, i.e. /aaa/bb?cc . In this case only RequestURI part of the original uri is replaced.
  • Relative path, i.e. xx?yy=abc . In this case the original RequestURI is updated according to the new relative path.

func (*URI) UpdateBytes

func (u *URI) UpdateBytes(newURI []byte)

UpdateBytes updates uri.

The following newURI types are accepted:

  • Absolute, i.e. http://foobar.com/aaa/bb?cc . In this case the original uri is replaced by newURI.
  • Absolute without scheme, i.e. //foobar.com/aaa/bb?cc. In this case the original scheme is preserved.
  • Missing host, i.e. /aaa/bb?cc . In this case only RequestURI part of the original uri is replaced.
  • Relative path, i.e. xx?yy=abc . In this case the original RequestURI is updated according to the new relative path.

func (*URI) Username

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

Username returns URI username

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

func (*URI) WriteTo

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

WriteTo writes full uri to w.

WriteTo implements io.WriterTo interface.

type UnsafeLinkBuffer

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

UnsafeLinkBuffer implements ReadWriter.

func (*UnsafeLinkBuffer) Append

func (b *UnsafeLinkBuffer) Append(w Writer) (err error)

Append implements Writer.

func (*UnsafeLinkBuffer) Bytes

func (b *UnsafeLinkBuffer) Bytes() []byte

Bytes returns all the readable bytes of this LinkBuffer.

func (*UnsafeLinkBuffer) Close

func (b *UnsafeLinkBuffer) Close() (err error)

Close will recycle all buffer.

func (*UnsafeLinkBuffer) Flush

func (b *UnsafeLinkBuffer) Flush() (err error)

Flush will submit all malloc data and must confirm that the allocated bytes have been correctly assigned.

func (*UnsafeLinkBuffer) GetBytes

func (b *UnsafeLinkBuffer) GetBytes(p [][]byte) (vs [][]byte)

GetBytes will read and fill the slice p as much as possible. If p is not passed, return all readable bytes.

func (*UnsafeLinkBuffer) IsEmpty

func (b *UnsafeLinkBuffer) IsEmpty() (ok bool)

IsEmpty check if this LinkBuffer is empty.

func (*UnsafeLinkBuffer) Len

func (b *UnsafeLinkBuffer) Len() int

Len implements Reader.

func (*UnsafeLinkBuffer) Malloc

func (b *UnsafeLinkBuffer) Malloc(n int) (buf []byte, err error)

Malloc pre-allocates memory, which is not readable, and becomes readable data after submission(e.g. Flush).

func (*UnsafeLinkBuffer) MallocAck

func (b *UnsafeLinkBuffer) MallocAck(n int) (err error)

MallocAck will keep the first n malloc bytes and discard the rest.

func (*UnsafeLinkBuffer) MallocLen

func (b *UnsafeLinkBuffer) MallocLen() (length int)

MallocLen implements Writer.

func (*UnsafeLinkBuffer) Next

func (b *UnsafeLinkBuffer) Next(n int) (p []byte, err error)

Next implements Reader.

func (*UnsafeLinkBuffer) Peek

func (b *UnsafeLinkBuffer) Peek(n int) (p []byte, err error)

Peek does not have an independent lifecycle, and there is no signal to indicate that Peek content can be released, so Peek will not introduce mcache for now.

func (*UnsafeLinkBuffer) ReadBinary

func (b *UnsafeLinkBuffer) ReadBinary(n int) (p []byte, err error)

ReadBinary implements Reader.

func (*UnsafeLinkBuffer) ReadByte

func (b *UnsafeLinkBuffer) ReadByte() (p byte, err error)

ReadByte implements Reader.

func (*UnsafeLinkBuffer) ReadString

func (b *UnsafeLinkBuffer) ReadString(n int) (s string, err error)

ReadString implements Reader.

func (*UnsafeLinkBuffer) Release

func (b *UnsafeLinkBuffer) Release() (err error)

Release the node that has been read. b.flush == nil indicates that this LinkBuffer is created by LinkBuffer.Slice

func (*UnsafeLinkBuffer) Skip

func (b *UnsafeLinkBuffer) Skip(n int) (err error)

Skip implements Reader.

func (*UnsafeLinkBuffer) Slice

func (b *UnsafeLinkBuffer) Slice(n int) (r Reader, err error)

Slice returns a new LinkBuffer, which is a zero-copy slice of this LinkBuffer, and only holds the ability of Reader.

Slice will automatically execute a Release.

func (*UnsafeLinkBuffer) Until

func (b *UnsafeLinkBuffer) Until(delim byte) (line []byte, err error)

Until returns a slice ends with the delim in the buffer.

func (*UnsafeLinkBuffer) WriteBinary

func (b *UnsafeLinkBuffer) WriteBinary(p []byte) (n int, err error)

WriteBinary implements Writer.

func (*UnsafeLinkBuffer) WriteBuffer

func (b *UnsafeLinkBuffer) WriteBuffer(buf *LinkBuffer) (err error)

WriteBuffer will not submit(e.g. Flush) data to ensure normal use of MallocLen. you must actively submit before read the data. The argument buf can't be used after calling WriteBuffer. (set it to nil)

func (*UnsafeLinkBuffer) WriteByte

func (b *UnsafeLinkBuffer) WriteByte(p byte) (err error)

WriteByte implements Writer.

func (*UnsafeLinkBuffer) WriteDirect

func (b *UnsafeLinkBuffer) WriteDirect(extra []byte, remainLen int) error

WriteDirect cannot be mixed with WriteString or WriteBinary functions.

func (*UnsafeLinkBuffer) WriteString

func (b *UnsafeLinkBuffer) WriteString(s string) (n int, err error)

WriteString implements Writer.

type WriteBodyStreamPanic

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

WriteBodyStreamPanic is returned when panic happens during writing body stream.

type Writer

type Writer interface {
	// Malloc returns a slice containing the next n bytes from the buffer,
	// which will be written after submission(e.g. Flush).
	//
	// The slice p is only valid until the next submit(e.g. Flush).
	// Therefore, please make sure that all data has been written into the slice before submission.
	Malloc(n int) (buf []byte, err error)

	// WriteString is a faster implementation of Malloc when a string needs to be written.
	// It replaces:
	//
	//  var buf, err = Malloc(len(s))
	//  n = copy(buf, s)
	//  return n, err
	//
	// The argument string s will be referenced based on the original address and will not be copied,
	// so make sure that the string s will not be changed.
	WriteString(s string) (n int, err error)

	// WriteBinary is a faster implementation of Malloc when a slice needs to be written.
	// It replaces:
	//
	//  var buf, err = Malloc(len(b))
	//  n = copy(buf, b)
	//  return n, err
	//
	// The argument slice b will be referenced based on the original address and will not be copied,
	// so make sure that the slice b will not be changed.
	WriteBinary(b []byte) (n int, err error)

	// WriteByte is a faster implementation of Malloc when a byte needs to be written.
	// It replaces:
	//
	//  var buf, _ = Malloc(1)
	//  buf[0] = b
	//
	WriteByte(b byte) (err error)

	// WriteDirect is used to insert an additional slice of data on the current write stream.
	// For example, if you plan to execute:
	//
	//  var bufA, _ = Malloc(nA)
	//  WriteBinary(b)
	//  var bufB, _ = Malloc(nB)
	//
	// It can be replaced by:
	//
	//  var buf, _ = Malloc(nA+nB)
	//  WriteDirect(b, nB)
	//
	// where buf[:nA] = bufA, buf[nA:nA+nB] = bufB.
	WriteDirect(p []byte, remainCap int) error

	// MallocAck will keep the first n malloc bytes and discard the rest.
	// The following behavior:
	//
	//  var buf, _ = Malloc(8)
	//  buf = buf[:5]
	//  MallocAck(5)
	//
	// equivalent as
	//  var buf, _ = Malloc(5)
	//
	MallocAck(n int) (err error)

	// Append the argument writer to the tail of this writer and set the argument writer to nil,
	// the operation is zero-copy, similar to p = append(p, w.p).
	Append(w Writer) (err error)

	// Flush will submit all malloc data and must confirm that the allocated bytes have been correctly assigned.
	// Its behavior is equivalent to the io.Writer hat already has parameters(slice b).
	Flush() (err error)

	// MallocLen returns the total length of the writable data that has not yet been submitted in the writer.
	MallocLen() (length int)
}

Writer is a collection of operations for nocopy writes.

The usage of the design is a two-step operation, first apply for a section of memory, fill it and then submit. E.g:

var buf, _ = Malloc(n)
buf = append(buf[:0], ...)
Flush()

Note that it is not recommended to submit self-managed buffers to Writer. Since the writer is processed asynchronously, if the self-managed buffer is used and recycled after submission, it may cause inconsistent life cycle problems. Of course this is not within the scope of the design.

func NewWriter

func NewWriter(w io.Writer) Writer

NewWriter convert io.Writer to nocopy Writer

type WriterFlusher

type WriterFlusher interface {
	Flush() error
	io.Writer
}

type WriterFlusherCloser

type WriterFlusherCloser interface {
	Flush() error
	io.Writer
}

Directories

Path Synopsis
examples
fileserver
Example static file server.
Example static file server.
Package expvarhandler provides fasthttp-compatible request handler serving expvars.
Package expvarhandler provides fasthttp-compatible request handler serving expvars.
Package fasthttpadaptor provides helper functions for converting net/http request handlers to fasthttp request handlers.
Package fasthttpadaptor provides helper functions for converting net/http request handlers to fasthttp request handlers.
Package fasthttputil provides utility functions for fasthttp.
Package fasthttputil provides utility functions for fasthttp.
Package reuseport provides TCP net.Listener with SO_REUSEPORT support.
Package reuseport provides TCP net.Listener with SO_REUSEPORT support.
Package stackless provides functionality that may save stack space for high number of concurrently running goroutines.
Package stackless provides functionality that may save stack space for high number of concurrently running goroutines.

Jump to

Keyboard shortcuts

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