Categorygithub.com/valyala/fasthttp
modulepackage
1.59.0
Repository: https://github.com/valyala/fasthttp.git
Documentation: pkg.go.dev

# README

fasthttp

Go Reference Go Report

FastHTTP – Fastest and reliable HTTP implementation in Go

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.

General info and links

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!

Related projects

  • 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 - :gear: 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.21.x and newer. Older versions might work, but won't officially 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.

# Packages

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 fasthttputil provides utility functions for fasthttp.
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 tcplisten provides customizable TCP net.Listener with various performance-related options: - SO_REUSEPORT.

# Functions

AcquireArgs returns an empty Args object from the pool.
AcquireCookie returns an empty Cookie object from the pool.
AcquireRequest returns an empty Request instance from request pool.
AcquireResponse returns an empty Response instance from response pool.
AcquireTimer returns a time.Timer from the pool and updates it to send the current time on its channel after at least timeout.
AcquireURI returns an empty URI instance from the pool.
AddMissingPort adds a port to a host if it is missing.
AppendBrotliBytes appends brotlied src to dst and returns the resulting dst.
AppendBrotliBytesLevel appends brotlied src to dst using the given compression level and returns the resulting dst.
AppendDeflateBytes appends deflated src to dst and returns the resulting dst.
AppendDeflateBytesLevel appends deflated src to dst using the given compression level and returns the resulting dst.
AppendGunzipBytes appends gunzipped src to dst and returns the resulting dst.
AppendGzipBytes appends gzipped src to dst and returns the resulting dst.
AppendGzipBytesLevel appends gzipped src to dst using the given compression level and returns the resulting dst.
AppendHTMLEscape appends html-escaped s to dst and returns the extended dst.
AppendHTMLEscapeBytes appends html-escaped s to dst and returns the extended dst.
AppendHTTPDate appends HTTP-compliant (RFC1123) representation of date to dst and returns the extended dst.
AppendInflateBytes appends inflated src to dst and returns the resulting dst.
AppendIPv4 appends string representation of the given ip v4 to dst and returns the extended dst.
AppendNormalizedHeaderKey appends normalized header key (name) to dst and returns the resulting dst.
AppendNormalizedHeaderKeyBytes appends normalized header key (name) to dst and returns the resulting dst.
AppendQuotedArg appends url-encoded src to dst and returns appended dst.
AppendUint appends n to dst and returns the extended dst.
AppendUnbrotliBytes appends unbrotlied src to dst and returns the resulting dst.
AppendUnquotedArg appends url-decoded src to dst and returns appended dst.
AppendUnzstdBytes appends unzstd src to dst and returns the resulting dst.
AppendZstdBytes appends zstd src to dst and returns the resulting dst.
CoarseTimeNow returns the current time truncated to the nearest second.
CompressHandler returns RequestHandler that transparently compresses response body generated by h if the request contains 'gzip' or 'deflate' 'Accept-Encoding' header.
CompressHandlerBrotliLevel returns RequestHandler that transparently compresses response body generated by h if the request contains a 'br', 'gzip' or 'deflate' 'Accept-Encoding' header.
CompressHandlerLevel returns RequestHandler that transparently compresses response body generated by h if the request contains a 'gzip' or 'deflate' 'Accept-Encoding' header.
Dial dials the given TCP addr using tcp4.
DialDualStack dials the given TCP addr using both tcp4 and tcp6.
DialDualStackTimeout dials the given TCP addr using both tcp4 and tcp6 using the given timeout.
DialTimeout dials the given TCP addr using tcp4 using the given timeout.
Do performs the given http request and fills the given http response.
DoDeadline performs the given request and waits for response until the given deadline.
DoRedirects performs the given http request and fills the given http response, following up to maxRedirectsCount redirects.
DoTimeout performs the given request and waits for response during the given timeout duration.
FileLastModified returns last modified time for the file.
FSHandler returns request handler serving static files from the given root folder.
GenerateTestCertificate generates a test certificate and private key based on the given host.
Get returns the status code and body of url.
GetDeadline returns the status code and body of url.
GetTimeout returns the status code and body of url.
ListenAndServe serves HTTP requests from the given TCP addr using the given handler.
ListenAndServeTLS serves HTTPS requests from the given TCP addr using the given handler.
ListenAndServeTLSEmbed serves HTTPS requests from the given TCP addr using the given handler.
ListenAndServeUNIX serves HTTP requests from the given UNIX addr using the given handler.
NewPathPrefixStripper returns path rewriter, which removes prefixSize bytes from the path prefix.
NewPathSlashesStripper returns path rewriter, which strips slashesCount leading slashes from the path.
NewStreamReader returns a reader, which replays all the data generated by sw.
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.
ParseByteRange parses 'Range: bytes=...' header value.
ParseHTTPDate parses HTTP-compliant (RFC1123) date.
ParseIPv4 parses ip address from ipStr into dst and returns the extended dst.
ParseUfloat parses unsigned float from buf.
ParseUint parses uint from buf.
Post
Post sends POST request to the given url with the given POST arguments.
ReleaseArgs returns the object acquired via AcquireArgs to the pool.
ReleaseCookie returns the Cookie object acquired with AcquireCookie back to the pool.
ReleaseRequest returns req acquired via AcquireRequest to request pool.
ReleaseResponse return resp acquired via AcquireResponse to response pool.
ReleaseTimer returns the time.Timer acquired via AcquireTimer to the pool and prevents the Timer from firing.
ReleaseURI releases the URI acquired via AcquireURI.
SaveMultipartFile saves multipart file fh under the given filename path.
Serve serves incoming connections from the given listener using the given handler.
ServeConn serves HTTP requests from the given connection using the given handler.
ServeFile returns HTTP response containing compressed file contents from the given path.
ServeFileBytes returns HTTP response containing compressed file contents from the given path.
ServeFileBytesUncompressed returns HTTP response containing file contents from the given path.
ServeFileUncompressed returns HTTP response containing file contents from the given path.
ServeFS returns HTTP response containing compressed file contents from the given fs.FS's path.
ServeTLS serves HTTPS requests from the given net.Listener using the given handler.
ServeTLSEmbed serves HTTPS requests from the given net.Listener using the given handler.
SetBodySizePoolLimit set the max body size for bodies to be returned to the pool.
StatusCodeIsRedirect returns true if the status code indicates a redirect.
StatusMessage returns HTTP status message for the given status code.
TimeoutHandler creates RequestHandler, which returns StatusRequestTimeout error with the given msg to the client if h didn't return during the given duration.
TimeoutWithCodeHandler creates RequestHandler, which returns an error with the given msg and status code to the client if h didn't return during the given duration.
VisitHeaderParams calls f for each parameter in the given header bytes.
WriteBrotli writes brotlied p to w and returns the number of compressed bytes written to w.
WriteBrotliLevel writes brotlied p to w using the given compression level and returns the number of compressed bytes written to w.
WriteDeflate writes deflated p to w and returns the number of compressed bytes written to w.
WriteDeflateLevel writes deflated p to w using the given compression level and returns the number of compressed bytes written to w.
WriteGunzip writes ungzipped p to w and returns the number of uncompressed bytes written to w.
WriteGzip writes gzipped p to w and returns the number of compressed bytes written to w.
WriteGzipLevel writes gzipped p to w using the given compression level and returns the number of compressed bytes written to w.
WriteInflate writes inflated p to w and returns the number of uncompressed bytes written to w.
WriteMultipartForm writes the given multipart form f with the given boundary to w.
WriteUnbrotli writes unbrotlied p to w and returns the number of uncompressed bytes written to w.
WriteUnzstd writes unzstd p to w and returns the number of uncompressed bytes written to w.

# Constants

Supported compression levels.
Supported compression levels.
Supported compression levels.
Supported compression levels.
Choose a default brotli compression level comparable to CompressDefaultCompression (gzip 6) See: https://github.com/valyala/fasthttp/issues/798#issuecomment-626293806.
Supported compression levels.
flate.DefaultCompression.
flate.HuffmanOnly.
Supported compression levels.
CookieSameSiteDefaultMode sets the SameSite flag.
CookieSameSiteDisabled removes the SameSite flag.
CookieSameSiteLaxMode sets the SameSite flag with the "Lax" parameter.
third-party cookies are phasing out, use Partitioned cookies instead.
CookieSameSiteStrictMode sets the SameSite flag with the "Strict" parameter.
DefaultConcurrency is the maximum number of concurrent connections the Server may serve by default (i.e.
DefaultDialTimeout is timeout used by Dial and DialDualStack for establishing TCP connections.
DefaultDNSCacheDuration is the duration for caching resolved TCP addresses by Dial* functions.
DefaultLBClientTimeout is the default request timeout used by LBClient when calling LBClient.Do.
DefaultMaxConnsPerHost is the maximum number of concurrent connections http client may establish per host by default (i.e.
DefaultMaxIdemponentCallAttempts is the default idempotent calls attempts count.
DefaultMaxIdleConnDuration is the default duration before idle keep-alive connection is closed.
DefaultMaxPendingRequests is the default value for PipelineClient.MaxPendingRequests.
DefaultMaxRequestBodySize is the maximum request body size the server reads by default.
FSCompressedFileSuffix is the suffix FS adds to the original file names when trying to store compressed file under the new file name.
FSHandlerCacheDuration is the default expiration duration for inactive file handlers opened by FS.
Content negotiation.
Client hints.
Headers.
Headers.
Headers.
Headers.
Other.
Headers.
Range requests.
Headers.
CORS.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Caching.
Response context.
Headers.
Authentication.
Headers.
Headers.
Connection management.
Downloads.
Headers.
Message body information.
Headers.
Headers.
Headers.
Headers.
Security.
Headers.
Headers.
Controls.
Headers.
Headers.
Do Not Track.
Headers.
Headers.
Conditionals.
Headers.
Headers.
Headers.
Headers.
Proxies.
Request context.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Server-sent event.
Headers.
Headers.
Redirects.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
WebSockets.
#nosec G101.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Transfer coding.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
Headers.
RFC 7231, 4.3.6.
RFC 7231, 4.3.5.
RFC 7231, 4.3.1.
RFC 7231, 4.3.2.
RFC 7231, 4.3.7.
RFC 5789.
RFC 7231, 4.3.3.
RFC 7231, 4.3.4.
RFC 7231, 4.3.8.
StateActive represents a connection that has read 1 or more bytes of a request.
StateClosed represents a closed connection.
StateHijacked represents a hijacked connection.
StateIdle represents a connection that has finished handling a request and is in the keep-alive state, waiting for a new request.
StateNew represents a new connection that is expected to send a request immediately.
RFC 7231, 6.3.3.
RFC 5842, 7.1.
RFC 7231, 6.6.3.
RFC 7231, 6.5.1.
RFC 7231, 6.5.8.
RFC 7231, 6.2.1.
RFC 7231, 6.3.2.
RFC 8297.
RFC 7231, 6.5.14.
RFC 4918, 11.4.
RFC 7231, 6.5.3.
RFC 7231, 6.4.3.
RFC 7231, 6.6.5.
RFC 7231, 6.5.9.
RFC 7231, 6.6.6.
RFC 3229, 10.4.1.
RFC 4918, 11.5.
RFC 7231, 6.6.1.
RFC 7231, 6.5.10.
RFC 4918, 11.3.
RFC 5842, 7.2.
RFC 7231, 6.5.5.
RFC 7540, 9.1.2.
RFC 7231, 6.4.2.
RFC 7231, 6.4.1.
RFC 4918, 11.1.
RFC 6585, 6.
RFC 7231, 6.3.5.
RFC 7231, 6.3.4.
RFC 7231, 6.5.6.
RFC 2774, 7.
RFC 7231, 6.5.4.
RFC 7231, 6.6.2.
RFC 7232, 4.1.
RFC 7231, 6.3.1.
RFC 7233, 4.1.
RFC 7231, 6.5.2.
RFC 7538, 3.
RFC 7232, 4.2.
RFC 6585, 3.
RFC 2518, 10.1.
RFC 7235, 3.2.
RFC 7233, 4.4.
RFC 7231, 6.5.11.
RFC 6585, 5.
RFC 7231, 6.5.7.
RFC 7231, 6.5.12.
RFC 7231, 6.3.6.
RFC 7231, 6.4.4.
RFC 7231, 6.6.4.
RFC 7231, 6.2.2.
RFC 7168, 2.3.3.
RFC 7231, 6.4.7.
RFC 6585, 4.
RFC 7235, 3.1.
RFC 7725, 3.
RFC 4918, 11.2.
RFC 7231, 6.5.13.
RFC 7231, 6.5.15.
RFC 7231, 6.4.5.
RFC 2295, 8.1.

# Variables

CookieExpireDelete may be set on Cookie.Expire for expiring the given cookie.
CookieExpireUnlimited indicates that the cookie doesn't expire.
ErrAlreadyServing is deprecated.
ErrBodyTooLarge is returned if either request or response body exceeds the given limit.
ErrConcurrencyLimit may be returned from ServeConn if the number of concurrently served connections exceeds Server.Concurrency.
ErrConnectionClosed may be returned from client methods if the server closes connection before returning the first response byte.
ErrConnPoolStrategyNotImpl is returned when HostClient.ConnPoolStrategy is not implement yet.
ErrDialTimeout is returned when TCP dialing is timed out.
ErrGetOnly is returned when server expects only GET requests, but some other type of request came (Server.GetOnly option is true).
HostClients are only able to follow redirects to the same protocol.
ErrMissingFile may be returned from FormFile when the is no uploaded file associated with the given multipart form key.
ErrMissingLocation is returned by clients when the Location header is missing on an HTTP response with a redirect status code.
ErrNoArgValue is returned when Args value with the given key is missing.
ErrNoFreeConns is returned when no free connections available to the given host.
ErrNoMultipartForm means that the request's Content-Type isn't 'multipart/form-data'.
ErrPerIPConnLimit may be returned from ServeConn if the number of connections per ip exceeds Server.MaxConnsPerIP.
ErrPipelineOverflow may be returned from PipelineClient.Do* if the requests' queue is overflowed.
ErrTimeout is returned from timed out calls.
ErrTLSHandshakeTimeout indicates there is a timeout from tls handshake.
ErrTooManyRedirects is returned by clients when the number of redirects followed exceed the max count.
FSCompressedFileSuffixes is the suffixes FS adds to the original file names depending on encoding when trying to store compressed file under the new file name.
NetHttpFormValueFunc gives consistent behavior with net/http.

# Structs

Args represents query arguments.
Client implements http client.
Cookie represents HTTP response cookie.
ErrBodyStreamWritePanic is returned when panic happens during writing body stream.
ErrBrokenChunk is returned when server receives a broken chunked body (Transfer-Encoding: chunked).
ErrDialWithUpstream wraps dial error with upstream info.
ErrNothingRead is returned when a keep-alive connection is closed, either because the remote closed it or because of a read timeout.
ErrSmallBuffer is returned when the provided buffer size is too small for reading request and/or response headers.
FS represents settings for request handler serving static files from the local filesystem.
HostClient balances http requests among hosts listed in Addr.
LBClient balances requests among available LBClient.Clients.
PipelineClient pipelines requests over a limited set of concurrent connections to the given Addr.
Request represents HTTP request.
RequestConfig configure the per request deadline and body limits.
RequestCtx contains incoming request and manages outgoing response.
RequestHeader represents HTTP request header.
Response represents HTTP response.
ResponseHeader represents HTTP response header.
Server implements HTTP server.
TCPDialer contains options to control a group of Dial calls.
URI represents URI :) .

# Interfaces

BalancingClient is the interface for clients, which may be passed to LBClient.Clients.
Logger is used for logging formatted messages.
Resolver represents interface of the tcp resolver.
RoundTripper wraps every request/response.

# Type aliases

ConnPoolStrategyType define strategy of connection pool enqueue/dequeue.
A ConnState represents the state of a client connection to a server.
CookieSameSite is an enum for the mode in which the SameSite flag should be set for the given cookie.
DialFunc must establish connection to addr.
DialFuncWithTimeout must establish connection to addr.
HijackHandler must process the hijacked connection c.
PathRewriteFunc must return new request path based on arbitrary ctx info such as ctx.Path().
RequestHandler must process incoming requests.
RetryIfErrFunc defines an interface used for implementing the following functionality: When the client encounters an error during a request, the behavior—whether to retry and whether to reset the request timeout—should be determined based on the return value of this interface.
RetryIfFunc defines the signature of the retry if function.
ServeHandler must process tls.Config.NextProto negotiated requests.
StreamWriter must write data to w.