Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http

Overview

fasthttp Build Status GoDoc Go Report Sourcegraph

FastHTTP – Fastest and reliable HTTP implementation in Go

Fast HTTP implementation for Go.

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)
  • 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 Go 1.13 as it provides some considerable 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)

Related projects

  • fasthttp - various useful helpers for projects based on fasthttp.
  • fasthttp-routing - fast and powerful routing package for fasthttp servers.
  • 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.
  • 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

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 should contain less bugs, since it is used and tested by much wider audience.
    • net/http works on Go older than 1.5.
  • 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?

    Go1.5+. Older versions won't be supported, since their standard package miss useful functions.

    NOTE: Go 1.9.7 is the oldest tested version. We recommend you to update as soon as you can. As of 1.11.3 we will drop 1.9.x support.

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

Comments
  • Fasthttp behind Aws load balancer. Keepalive conn are causing trouble

    Fasthttp behind Aws load balancer. Keepalive conn are causing trouble

    Hi!

    We're using a light/fast fasthttp server as a proxy in our services infrastructure. However, we've been experiencing some issues when we use an amazon Load Balancer. Sometimes (and this is randomly) the ALB returns 502 because the request can't find the fasthttp service. Note that ALB uses keepalive connections by default and that can't be changed.

    After a while doing some research, we were suspicious that fasthttp was closing the keepalive connections at some point, and the ALB couldn't re-use it, so it would return a 502.

    If we set the Server.DisableKeepAlive = true everything works as expected (with a lot more of load of course)

    We reduced our implementation to the minimum to test:

    s := &fasthttp.Server{
    		Handler:     OurHandler,
    		Concurrency: fasthttp.DefaultConcurrency,
    	}
    	s.DisableKeepalive = true // If this is false, we see the error randomly.
    
    	log.Fatal(s.ListenAndServe(":" + strconv.Itoa(port)))
    
    

    The handler basically does this:

            // h is an instance of *fasthttp.HostClient configured with some parameters
    	if err := h.proxy.Do(req, resp); err != nil {
    		log.Error("error when proxying the request: ", err)
    	}
    

    Is there any chance someone has experienced this? I'm not sure how we should proceed with the keepalive connections in the fasthttp.Server, as we are using pretty much all the default parameters.

    Thanks in advance!

    bug help wanted pending/submitter-response 
    opened by Rulox 42
  • CORS: allow every origin with credentials

    CORS: allow every origin with credentials

    I have a simple question. I want to set "Access-Control-Allow-Credentials" to "true" and "Access-Control-Allow-Origin" to the current request origin, so every origin is allowed to access my API. Which method should I use on the RequestCtx to retrieve the current request origin which is eligible to show up in the CORS header? I tried different ones like ctx.RemoteAddr.String() or ctx.Request.URI().Host() but none of them worked.

    I want that because I want to achieve a JWT authentication using the Authorization header, which is only received if I allow credentials.

    Greetings

    question 
    opened by lus 40
  • Reponse body io.Reader

    Reponse body io.Reader

    Hey guys. How to set custom response body writer? I've tried to use SetBodyStream, but i don't see any body readers from response which i need to pass in io.Reader. P.S I'm trying to implement throttler.

    enhancement wontfix 
    opened by qJkee 40
  • Too many timeouts when working with high concurrency

    Too many timeouts when working with high concurrency

    I use fasthttp client in an application that collects information about millions of sites on the network. To do this really quickly and in parallel, I create a bunch of goroutines in which I execute c.httpClient.DoTimeout (...) requests

    If I run no more than ~ 100 threads per core, then I successfully receive answers for all requests. If I run more than 100 threads per core, then part of the requests will be interrupted by timeout and I will get errors

    The problem is definitely not in the sites themselves.

    I think there are some restrictions on the number of open connections or something like that, but I don’t know where to dig.

    I will be very glad to any prompts.

    pending/investigation 
    opened by scanpatch 26
  • the master branch's code is ok ?

    the master branch's code is ok ?

    1、today i go get new fasthttp code, i found when the browse send a request, somtimes it recevie a error message "Error when parsing request"

    2、why use os.Command().Output() int my handler, the bin will output "child exited" ?

    pending/investigation 
    opened by goith 26
  • Error 7 at 1-3 Open Connections

    Error 7 at 1-3 Open Connections

    Hi there,

    I'm currently at a loss as to what is bottle necking. As soon as I hit fasthttp with +1000 reqs/s (same origin), it starts to fail. Curl is throwing: curl: (7) Couldn't connect to server.

    I'm using fasthttp with fasthttp-router and their default configurations. Seeing that Open Connections is always below 5 from 262144 I don't see what could be causing this and have my doubts of it being caused by the app.

    Could this be a limit from the OS it self, are there any unix settings we need to change? In terms of connections we are using net.core.somaxconn = 16384

    Thanks for you help

    opened by Slind14 24
  • Response.ContentLength Not correct

    Response.ContentLength Not correct

    Code:

    if len(string(resp.Body())) > 0 {
    	logs.DebugLog( "i got %d %s", resp.Header.ContentLength(), resp.String() )
    }
    

    #read log: [[DEBUG]]11:18:38 task.go:105: i got 90 HTTP/1.1 206 Partial Content Date: Mon, 25 May 2020 08:18:38 GMT Content-Type: text/plain; charset=utf-8 Content-Length: 89

    What??? resp.Header.ContentLength()=90, resp.String() thinks different

    (I found this paradox out when wrote code:

    If resp.Header.ContentLength() > 0 {
    logs.StatusLog(resp.Body() )
    }
    

    and got many empty row on log ! Reading body is not match performance on empty response :-) )

    *Go 1.14 *github.com/valyala/fasthttp v1.9.0

    opened by ruslanBik4 20
  • Panics at on context close, v1.33.0

    Panics at on context close, v1.33.0

    Hello, unfortunately there are no more details except this message I could find.

    panic: runtime error: invalid memory address or nil pointer dereference
    [signal SIGSEGV: segmentation violation code=0x1 addr=0x200 pc=0x901667]
    
    goroutine 19473 [running]:
    github.com/valyala/fasthttp.(*RequestCtx).Done(0x8c4639)
            /go/src/dsp/vendor/github.com/valyala/fasthttp/server.go:2691 +0x7
    context.propagateCancel.func1()
            /usr/local/go/src/context/context.go:280 +0x50
    created by context.propagateCancel
            /usr/local/go/src/context/context.go:278 +0x1d0
    
    opened by Gaudeamus 19
  • Suggestion: Continuous Fuzzing

    Suggestion: Continuous Fuzzing

    Hi, I'm Yevgeny Pats Founder of Fuzzit - Continuous fuzzing as a service platform.

    We have a free plan for OSS and I would be happy to contribute a PR if that's interesting. The PR will include the following

    • go-fuzz fuzzers (This is generic step not-connected to fuzzit)
    • Continuous Fuzzing of master branch which will generate new corpus and look for new crashes
    • Regression on every PR that will run the fuzzers through all the generated corpus and fixed crashes from previous step. This will prevent new or old bugs from crippling into master.

    You can see our basic example here and you can see an example of "in the wild" integration here.

    Let me know if this is something worth working on.

    might be related to this https://github.com/valyala/fasthttp/issues/33

    Cheers, Yevgeny

    pending/development 
    opened by yevgenypats 19
  • Reverse Proxy?

    Reverse Proxy?

    The golang httputil package has a ReverseProxy that will serve from an http.Request.

    Is there any comporable revrese proxy for fasthttp that will serve from a fasthttp.Request?

    enhancement question 
    opened by caleblloyd 19
  • I had write a simply httpproxy by fasthttp,but I had test the speed find the qps is so bad

    I had write a simply httpproxy by fasthttp,but I had test the speed find the qps is so bad

    fasthttp proxy wrk report that:

      ./wrk -c 1000 -t 1000 -d 30s http://127.0.0.1:8080/
    Running 30s test @ http://127.0.0.1:8080/
      1000 threads and 1000 connections
      Thread Stats   Avg      Stdev     Max   +/- Stdev
        Latency   123.28ms  283.75ms   1.99s    88.85%
        Req/Sec    49.95     49.44   653.00     68.67%
      103307 requests in 30.12s, 12.31MB read
      Socket errors: connect 0, read 0, write 0, timeout 2795
      Non-2xx or 3xx responses: 2136
    Requests/sec:   3429.97
    Transfer/sec:    418.45KB
    

    I use nginx proxy reports this:

     ./wrk -c 1000 -t 1000 -d 30s http://127.0.0.1:5555/
    Running 30s test @ http://127.0.0.1:5555/
      1000 threads and 1000 connections
      Thread Stats   Avg      Stdev     Max   +/- Stdev
        Latency   245.24ms  329.09ms   1.25s    79.48%
        Req/Sec    42.25     35.39     1.97k    60.26%
      434163 requests in 30.11s, 100.60MB read
      Socket errors: connect 0, read 0, write 0, timeout 604
    Requests/sec:  14421.42
    Transfer/sec:      3.34MB
    

    the fasthttp proxy code is that:

    package main
    import (
        "github.com/valyala/fasthttp"
        "time"
    )
    func test(ctx *fasthttp.RequestCtx){
      time.Sleep(100)
      ctx.WriteString("ok ")
    }
    func proxytest( ctx *fasthttp.RequestCtx){
    
        s:= &fasthttp.HostClient{Addr:"127.0.0.1:666"}
        req:=fasthttp.AcquireRequest()
        resp:=fasthttp.AcquireResponse()
        defer fasthttp.ReleaseRequest(req)
        defer fasthttp.ReleaseResponse(resp)
        ctx.Request.CopyTo(req)
        err:=s.Do(req,resp )
        if err!=nil{
            ctx.Error(err.Error(),504  )
        }
        resp.Header.Add("Server","waf")
        resp.WriteTo( ctx.Conn())
    }
    func main() {
    
        web:=&fasthttp.Server{Handler:proxytest }
        test:=&fasthttp.Server{ TCPKeepalive:true,TCPKeepalivePeriod:30*time.Second  ,  Handler:test }
        go test.ListenAndServe(":666")
        web.ListenAndServe(":8080")
        
    }
    

    the nginx conf is that:

    location /
    {
        proxy_pass http://127.0.0.1:666;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header REMOTE-HOST $remote_addr;
        
    
        add_header X-Cache $upstream_cache_status;
        
        
    }
    

    why nginx is Requests/sec: 14421.42 ,but the fasthttp proxy is Requests/sec: 3429.97. how to improve my code

    opened by 59duncom 18
  • http client throttling

    http client throttling

    I using the fasthttp for an OpenRTB proxy that receives JSON requests from SSP, changes incoming json and forwards to other DSPs. Under a heavy load I see in CPU profile that almost all CPU is spent on connection to DSPs: Dial, then Syscall6 (Write). Load average is multiple time higher than CPUs count. The http client returns a lot of net.OpError errors. The MaxConnsPerHost is 20480 and MaxIdleConnDuration is 1 hour so the keep alive should work fine.

    As far I understood this happens because: We have a load of 10000 QPS but each requests is processed in 100ms e.g. we need 1000 parallel connections to a DSP. But when we reached a conn limit of the DSP itself our request is failed with connection's net.OpError. But the http client keeps to try to establish new connections and this eats all the CPU.

    I tried to implement a simple throttling that makes a 400ms delay when on connection error occurs. It looks like:

    var hostClient fasthttp.HostClient
    var throttlingEnabled atomic.Bool
    var throttlingStarted time.Time
    var throttlingDelay = 400 * time.Millisecond
    
    func performRequest(req *fasthttp.Request, res *fasthttp.Response) {
    	if throttlingEnabled.Load() {
    		if time.Now().Sub(throttlingStarted) > throttlingDelay {
    			throttlingEnabled.Store(false)
    			log.Printf("throtling: disable\n")
    		} else {
    			log.Printf("throtling: skip request\n")
    		}
    		return
    	}
    	requestTimeout := 200 * time.Millisecond
    	connErr := hostClient.DoTimeout(req, res, requestTimeout)
    	errName := reflect.TypeOf(connErr).String()
    	if errName == "*net.OpError" {
    		throttlingEnabled.Store(true)
    		throttlingStarted = time.Now()
    	}
    }
    

    Now the processed QPS fallen down at least twice but yes, no any load spikes. Is anything better than the solution? Maybe I can reuse the rate.Limiter from golang.org/x/time/rate package. I see that the PipedClient do have some throttling so maybe something similar can be added to a HostClient? We need something that will work smarter and with recovery from a heavy load.

    Another one question is what will happen if the connection and TLS handshake takes longer than the DoTimeout() timeout? For example connection takes 200ms but the request timeout is 100ms. Then it looks like no any connection will ever established.

    Do we have any article/documentation on configuring a server for a heavy load? Like increase allowed opened files in systemd unit to DefaultLimitNOFILE=524288 and etc. Can anyone recommend to me something to read.

    opened by stokito 3
  • mustDiscard() panics and the whole server crashes

    mustDiscard() panics and the whole server crashes

    In fasthttp, in file header.go, this function:

    func mustDiscard(r *bufio.Reader, n int) {
    	if _, err := r.Discard(n); err != nil {
    		panic(fmt.Sprintf("bufio.Reader.Discard(%d) failed: %v", n, err))
    	}
    }
    

    sometimes, under high concurrency, panics with error panic: bufio.Reader.Discard(517) failed: read tcp4 ADDR-1->:8081->ADDR-2:30116: i/o timeout and the server crashes.

    Why it is not handled by error? Because the panic is on the side of the worker, and the thrown panic cannot be recovered by any of the RouterPanic or Recovery middleware. What should be done here?

    opened by mostafatalebi 5
  • fasthttp.SaveMultipartFile() generate tmp file without clean

    fasthttp.SaveMultipartFile() generate tmp file without clean

    After fasthttp.SaveMultipartFile(file, filePath) for several files I found the tmp file under /tmp was not cleaned, is this designed behavior? how could I get the tmp file path for each SaveMultipartFile and remove after file received?

    $ ls /tmp
    multipart-1116084598  multipart-1806005773  multipart-2359895161  multipart-2868180902  multipart-3505259536  multipart-4200780900  multipart-957202837
    multipart-1432350850  multipart-2089011025  multipart-2449044315  multipart-2881117185  multipart-3587317179  multipart-423553165
    multipart-147667864   multipart-2165895272  multipart-2650738835  multipart-3031107618  multipart-371009225   multipart-520911278
    multipart-1499565166  multipart-2181355762  multipart-2700390650  multipart-3223448677  multipart-3975570320  multipart-687744821
    multipart-1576810887  multipart-2347928608  multipart-2827028297  multipart-3254124333  multipart-408984157   multipart-931328463
    
    opened by laoshanxi 4
  • When i used fasthttp send Get request, cpu rise to 100% occasionally 5 - 10s .

    When i used fasthttp send Get request, cpu rise to 100% occasionally 5 - 10s .

    My service deploy on server as a log transfer, QPS about 18000/s, QPM about 1000000/s. In order to make each nginx worker running balance ,so I config maxidelConnDuration to 20ms for making each idle connection close in advance, the connect will restart establish with nginx worker.

    Here is my fasthttp config: { Readtimeout: 300ms, Writetimeout:300ms, maxidleConnDuration:20ms, }

    Howerver, the cpu rise to 100% occasionally keep 5 ~ 10s, and then the cpu usage down to the normal.When I remove the Writetimeout, it means the Writetimeout is unlimited, cpu usage will not rise to 100% anymore. I have no idea why this happend.

    opened by arhken666 4
Releases(v1.43.0)
  • v1.43.0(Nov 28, 2022)

    • dbf457e Revert "feat: support mulit/range (#1398)" (#1446) (Erik Dubbelboer)
    • c50de95 client.go fix addMissingPort() (#1444) (Sergey Ponomarev)
    Source code(tar.gz)
    Source code(zip)
  • v1.42.0(Nov 24, 2022)

    • 4995135 feat: add ShutdownWithContext (#1383) (kinggo)
    • 7b3bf58 style: modify typo and remove repeated type conversions (#1437) (kinggo)
    • 8f43443 Wait for the response of pipelineWork in background and return it to pool (#1436) (Andy Pan)
    • c367454 Fix some potential pool leaks (#1433) (Andy Pan)
    • b32a3dd Use time.Until(deadline) instead of -time.Since(deadline) (#1434) (Andy Pan)
    • 8a60232 Assert with *net.TCPConn instead of *net.TCPListener in acceptConn() for TCP sockets (#1432) (Andy Pan)
    • c57a2ce Make sure nothing is nil in tmp slice (#1423) (hs son)
    • f095481 Request.SetTimeout (#1415) (brian-armstrong-discord)
    • c88dd5d fix form empty field error when used with pipe (#1417) (nick9822)
    • a468a7d feat: support mulit/range (#1398) (byene0923)
    • 3963a79 feat: add PeekKeys and PeekTrailerKeys (#1405) (kinggo)
    • eca86de fix: (#1410) (byene0923)
    • e214137 fix: ignore body should not set content-length of streaming (#1406) (byene0923)
    Source code(tar.gz)
    Source code(zip)
  • v1.41.0(Oct 25, 2022)

    • 128e9b3 optimize: adjust the behavior of PeekAll based on VisitAll (#1403) (kinggo)
    • 2c8ce3b feat: add header.PeekAll (#1394) (kinggo)
    • d404f2d make RequestCtx's userdata accept keys that are of type: interface{} (#1387) (pj)
    • bcf7e8e test: merge test in adaptor_test.go (#1381) (kinggo)
    • 31fdc79 resolve CVE-2022-27664 (#1377) (Craig O'Donnell)
    • 40eec0b byte to string unsafe conversion in fasthttpadaptor ConvertRequest method (#1375) (Emre Savcı)
    • a696949 Deprecate Go 1.15 (#1379) (Aoang)
    Source code(tar.gz)
    Source code(zip)
  • v1.40.0(Sep 6, 2022)

    • 2f1e949 Improve isTLSAlready check (Erik Dubbelboer)
    • 404c8a8 Chore (#1365) (tyltr)
    • 79ccfff Don't use tls ClientSessionCache (Erik Dubbelboer)
    • 28bec71 Fix "use of closed network connection" error check (Erik Dubbelboer)
    • 3b147b7 Fix(server): reset maxRequestBodySize to the server's config (#1360) (Geralt X Li)
    • af94725 Reduce slice growth in adaptor (#1356) (Qing Moy)
    Source code(tar.gz)
    Source code(zip)
  • v1.39.0(Aug 15, 2022)

    • ea60524 Add Go 1.19 Support (#1355) (Aoang)
    • a5f448f Improve Client timeout (#1346) (Erik Dubbelboer)
    • 42f83c6 Prevent overflow and panic on large HTTP responses (#1351) (mathew)
    • f3513cc Introduce FS.CompressRoot (#1331) (mojatter)
    • c94be05 use timeout insteadof read/writetimeout when timeout lower than read/… (#1336) (fare83)
    • b23c5e9 Close new connections after 5s in closeIdleConns (Erik Dubbelboer)
    • 5b0cbf2 Fix apparent documentation typo (#1330) (kayos)
    Source code(tar.gz)
    Source code(zip)
  • v1.38.0(Jun 27, 2022)

    • 16d30c4 Support AIX SO_REUSEADDR and SO_REUSEPORT (#1328) (zhangyongding)
    • bc24f9d Consolidate TCPKeepalive in server.Serve (#1320) (#1324) (Y.Horie)
    • 8a32089 Add ConnPoolStrategy field to client (#1317) (Thearas)
    • 35aca7b BodyDecoded() for request and responses (#1308) (Sergey Ponomarev)
    • 66cd502 header.go Referer() optimize (#1313) (Sergey Ponomarev)
    • c9f43ea Response.ContentEncoding(): store as field and avoid using Header.SetCanonical() (#1311) (Sergey Ponomarev)
    • de18824 Optimize server connection close logic (#1310) (Sergey Ponomarev)
    Source code(tar.gz)
    Source code(zip)
  • v1.37.0(May 17, 2022)

  • v1.36.0(Apr 27, 2022)

    • 7cc6f4c Fix DoTimeout Streaming body bug (Erik Dubbelboer)
    • 9a0b4d0 optimize (#1275) (tyltr)
    • e3d2512 optimize (#1272) (tyltr)
    • b40b5a4 Update tlsClientHandshake (#1263) (Mikhail Faraponov)
    • c7576cc Added Windows support and removed some panics (#1264) (Mauro Leggieri)
    • f0e1be5 add nil check of req.body and resp.body on ReleaseBody (#1266) (zzzzwc)
    Source code(tar.gz)
    Source code(zip)
  • v1.35.0(Apr 5, 2022)

    • 7a5afdd Use %v for errors and %q for strings (#1262) (Erik Dubbelboer)
    • e4a541f support adding/removing clients from LBClient (#1243) (Cam Sweeney)
    • b4152d1 Only set RequestCtx.s once (Erik Dubbelboer)
    • d4c739e State active (#1260) (Erik Dubbelboer)
    • f3bce3a Add Go 1.18 support (#1253) (Aoang)
    • c674263 Fix race conditions in tests (Erik Dubbelboer)
    • 286828e add a test for AppendQuotedArg (#1255) (ZhangYunHao)
    • 2044e1e reduce unnessary type assart (#1254) (tyltr)
    • 3101938 Imporve AppendHTMLEscape fast path (#1249) (ZhangYunHao)
    • d1753f7 bytesconv: add appropriate build tags for s390x (#1250) (Nick Rosbrook)
    • 8f5e51f Add connection pool queuing strategies in HostClient. (#1238) (Y.Horie)
    • f7423e3 Fix AppendHTMLEscape (#1248) (ZhangYunHao)
    • 1a5f2f4 Read response when client closes connection #1232 (#1233) (ArminBTVS)
    Source code(tar.gz)
    Source code(zip)
  • v1.34.0(Mar 7, 2022)

    • 59f94a3 Update github.com/klauspost/compress (#1237) (Mikhail Faraponov)
    • 62c15a5 Don't reset RequestCtx.s (#1234) (Erik Dubbelboer)
    • 7670c6e Fix windows tests (#1235) (Erik Dubbelboer)
    • f54ffa1 feature: Keep the memory usage of the service at a stable level (#1216) (Rennbon)
    • 15262ec Warn about unsafe ServeFile usage (#1228) (Erik Dubbelboer)
    • 1116d03 Fix panic while reading invalid trailers (Erik Dubbelboer)
    • 856ca8e Update dependencies (#1230) (Mikhail Faraponov)
    • 6b5bc7b Add windows support to normalizePath (Erik Dubbelboer)
    • f0b0cfe Don't log ErrBadTrailer by default (Erik Dubbelboer)
    • 6937fee fix: (useless check), skip Response body if http method HEAD (#1224) (Pavel Burak)
    • b85d2a2 Fix http proxy behavior (#1221) (Aoang)
    • ad8a07a RequestHeader support set no default ContentType (#1218) (Jack.Ju)
    • c94581c support configure HostClient (#1214) (lin longhjui)
    • 632e222 Client examples (#1208) (Sergey Ponomarev)
    • 6a3cc23 uri_test.go use example.com for clearness (#1212) (Sergey Ponomarev)
    • 9d665e0 Update dependencies (#1204) (Mikhail Faraponov)
    • 8d7953e Fix scheme check for not yet parsed requests (#1203) (ArminBTVS)
    Source code(tar.gz)
    Source code(zip)
  • v1.33.0(Jan 27, 2022)

    • 61aa8b1 remove redundant code (#1202) (tyltr)
    • 4369776 fix(hijack): reuse RequestCtx (#1201) (Sergio VS)
    • 2aca3e8 fix(hijack): reset userValues after hijack handler execution (#1199) (Sergio VS)
    • 9123060 Updated dependencies (#1194) (Mikhail Faraponov)
    Source code(tar.gz)
    Source code(zip)
  • v1.32.0(Jan 10, 2022)

    • 7eeb00e Make tests less flaky (#1189) (Erik Dubbelboer)
    • d19b872 Update tcpdialer.go (#1188) (Mikhail Faraponov)
    • c727b99 Release UseHostHeader in ReleaseRequest() (#1185) (Tolyar)
    • 6c0518b Fix UseHostHeader for DoTimeout + tests (#1184) (Tolyar)
    • 6b55811 Add MaxIdleWorkerDuration to Server. (#1183) (Kilos Liu)
    • 4517204 Allow to set Host header for Client (#1169) (Tolyar)
    • 258a4c1 fix: reset response after reset user values on keep-alive connections (#1176) (Sergio VS)
    • e9db537 Use %w to wrap errors (#1175) (Erik Dubbelboer)
    • 7db0597 Fix bad request trailer panic (Erik Dubbelboer)
    • 4aadf9a Fix parseTrailer panic (Erik Dubbelboer)
    • da7ff7a Add trailer support (#1165) (ichx)
    • 017f0aa fix: reset request after reset user values on keep-alive connections (#1162) (Sergio VS)
    • 3b117f8 feat: close idle connections when server shutdown (#1155) (ichx)
    • a94a2c3 Remove redundant code (#1154) (ichx)
    • f7c354c Fix race condition in Client.mCleaner (Erik Dubbelboer)
    • c078a9d Add string and bytes buffer convert trick in README (#1151) (ichx)
    • 3ff6aaa uri: isHttps() and isHttp() (#1150) (Sergey Ponomarev)
    • 8febad0 http.go: Request.SetURI() (Fix #1141) (#1148) (Sergey Ponomarev)
    • 2ca01c7 fix: Status Line parsing and writing (#1135) (Shivansh Vij)
    • 931d0a4 Fix lint (Erik Dubbelboer)
    • d613502 use sync.map is better (#1145) (halst)
    • c15e642 Don't run all race tests on windows (#1143) (Erik Dubbelboer)
    • 6006c87 chore (#1137) (tyltr)
    • 6d4db9b Fix race condition in getTCPAddrs (Erik Dubbelboer)
    • 528dd62 feat: ability to read body separate from header (#1130) (Shivansh Vij)
    • 556aa81 feat: ability to edit status messages (#1126) (Valentin Paz Marcolla)
    • 4cfec1a feat: make public Server.TLSConfig (#1128) (Sergio VS)
    • fe7d90e remove redundant code (#1127) (tyltr)
    Source code(tar.gz)
    Source code(zip)
  • v1.31.0(Oct 11, 2021)

    • 81fc968 Add warning to readme (Erik Dubbelboer)
    • 7fdd526 feat: a new userData API Remove (#1117) (tyltr)
    • f307299 feat:no need to store nil (#1116) (tyltr)
    • ad6d128 URI.Parse should never change it's input (Erik Dubbelboer)
    • ffab77a Improve return value reusability documentation (Erik Dubbelboer)
    • 542a203 Properly parse URI (Erik Dubbelboer)
    • 711e421 feat: improve TCPDialer by sync.map instead of map+mutex (#1106) (tyltr)
    • adc0e57 Remove useless runtime.KeepAlive (#1107) (Oleg Kovalov)
    • 44d0333 fix: typo (#1105) (tyltr)
    • 06b464f fix typo in deadline (#1099) (Evgenii)
    • 46d9235 Check go fmt during lint (#1097) (Erik Dubbelboer)
    Source code(tar.gz)
    Source code(zip)
  • v1.30.0(Sep 9, 2021)

    • 713da4e Adding new compressible prefixes (#1092) (Kyle Unverferth)
    • 1647255 remove unnecessary op (#1095) (tyltr)
    • f0a2189 feat: improve IsMethod (#1088) (tyltr)
    • 5d73da3 Update status.go (#1093) (Mikhail Faraponov)
    • 3f70d78 Some FS tests can't run in parallel (Erik Dubbelboer)
    • ba40107 compatible with new build tag (#1087) (tyltr)
    • d9c7573 improve invalidStatusLine by appending a []byte directly (#1086) (tyltr)
    • cad867a Remove the redundant badage (#1085) (Andy Pan)
    • 38992da Fix []byte reuse bug (Erik Dubbelboer)
    • 6321103 Various deadline fixes (#1081) (Erik Dubbelboer)
    • 51508d7 Fix various Windows Github Action errors (#1082) (Erik Dubbelboer)
    • c7ce95f Fix s2b (#1079) (YenForYang)
    • a50f59b Increase various test timeouts (Erik Dubbelboer)
    • 0fe8cdd Optimize size of Server by moving bool fields (#1077) (Lanco)
    • a6f9c8a Fix Client doc and mCleaner (#1076) (Erik Dubbelboer)
    • 5a6e6e1 Add Go 1.17 support (#1074) (Erik Dubbelboer)
    Source code(tar.gz)
    Source code(zip)
  • v1.29.0(Aug 17, 2021)

    • 97e1319 Update compress (#1069) (Mikhail Faraponov)
    • 0263cae Fix FasthttpSocksDialer example (Erik Dubbelboer)
    • d31e6db Handle perIPConn in RequestCtx.IsTLS() specially (#1064) (Tianyi Song)
    • 9466cd7 fix typo: occured -> occurred (#1061) (Kazumasa Takenaka (Bamboo))
    • b3ece39 Update README.md (#1058) (Darío)
    • d0df1e1 Add ResetUserValues() and test (#1056) (Sujit Baniya)
    Source code(tar.gz)
    Source code(zip)
  • v1.28.0(Jun 30, 2021)

    • 1504a84 Increase TestHostClientMaxConnWaitTimeoutSuccess timeout (Erik Dubbelboer)
    • f6560be Flush buffered responses if we have to wait for the next request (#1050) (Erik Dubbelboer)
    Source code(tar.gz)
    Source code(zip)
  • v1.27.0(Jun 21, 2021)

    • 874c8ca Increase timeouts for Windows github actions (Erik Dubbelboer)
    • 924a63f Increase TestServerTLSReadTimeout timeout (Erik Dubbelboer)
    • 410bde6 Fix race condition in TestPipelineClientIssue832 (Erik Dubbelboer)
    • 9f2c636 Lower go test time (Erik Dubbelboer)
    • 4ed933a fix: set content-length properly when StreanRequestBody was enabled (#1049) (Meng)
    • cec9953 Add IdleTimeout to Shutdown documentation (Erik Dubbelboer)
    • c12a061 TCPDialer :: DNSCacheDuration option (#1046) (Ertuğrul Emre Ertekin)
    • 87fc958 Run go test on github actions (#1047) (Erik Dubbelboer)
    • be13b50 Defined Transport for the client (#1045) (Darío)
    • b8b065b Don't unwrap io.LimitedReader (Erik Dubbelboer)
    Source code(tar.gz)
    Source code(zip)
  • v1.26.0(Jun 1, 2021)

    • 6233fbc Fix header .Add functions (#1036) (Erik Dubbelboer)
    • 5bb5cfc Remove unused peekRawHeader (Erik Dubbelboer)
    • 7d13e18 Add Request.TLS and try to avoid a new alloc if Request.Header is already allocated (#1034) (Sergio Andrés Virviescas Santana)
    • b433ecf Make sure to reset the userValues always and at the exact time (#1027) (Sergio Andrés Virviescas Santana)
    • a18c632 Fix cookie panic (Erik Dubbelboer)
    • f3e4118 Don't recommend Go 1.13 (Erik Dubbelboer)
    Source code(tar.gz)
    Source code(zip)
  • v1.25.0(May 20, 2021)

    • fa3e5d8 Run test with go 1.16.X (#1028) (Sergio Andrés Virviescas Santana)
    • ffa0cab Use proper content-type when it is not present (#1023) (MoreFreeze)
    • 04cde74 feature: add ConvertRequest func (#1024) (Nícolas Barbosa)
    • 5898006 Upgrade dependencies and tidy (#1029) (Sergio Andrés Virviescas Santana)
    • 097fa05 Fix ignoreBody still set content length (#1022) (MoreFreeze)
    • b2f111b Fix(adaptor): Fixed an issue where the adapter did not convert all (#1021) (Juan Chan)
    • 19fcd40 Fix chunked streaming (#1015) (Roman Khimov)
    Source code(tar.gz)
    Source code(zip)
  • v1.24.0(Apr 28, 2021)

  • v1.23.0(Mar 29, 2021)

    • 2a6f7db Adding support for securing error logs (#1001) (Daniel Firsht)
    • e61c9d5 Improve Client/HostClient pooling when many HostClient structs created and removed during program execution (#1000) (Mikhail Faraponov)
    • a583006 Use bytes.IndexByte instead of bytes.Index for single byte lookup (#999) (Mike Faraponov)
    • 860c345 Fix unexpected panic when calling Do of a PipelineClient (#997) (blanet)
    • 0cd7349 ImmediateHeaderFlush when no body (#995) (Vladimir Shteinman)
    • 02e0722 Add PipelineClient name (#994) (kiyon)
    • 1a7995b format err info (#989) (peakle)
    • f40ea7e Improve socks proxy (#990) (kiyon)
    • 34fa9a6 Add DisableHeaderNamesNormalizing to PipelineClient (#991) (kiyon)
    Source code(tar.gz)
    Source code(zip)
  • v1.22.0(Mar 1, 2021)

    • 4637395 Update deps (Erik Dubbelboer)
    • c3cd5e1 Export HostClient.connsCount (#981) (kiyon)
    • a4b0703 Implemented DisablePathNormalizing in PipelineClient (#977) (Seva Maltsev)
    • 0880335 Update compress.go (#978) (Mike Faraponov)
    • e7294d2 Update client.go (#979) (Mike Faraponov)
    • 62dfc52 Fix Client ms cleaner (#975) (kiyon)
    Source code(tar.gz)
    Source code(zip)
  • v1.21.0(Feb 17, 2021)

    • 3cd0862 Streaming fixes (#970) (Erik Dubbelboer)
    • 1b61ca2 Added Protocol() as a replacement of hardcoded strHTTP11 (#969) (Darío)
    • 52a8ab6 fix s2b go vet warning (#967) (ZhangYunHao)
    Source code(tar.gz)
    Source code(zip)
  • v1.20.0(Feb 8, 2021)

    • a88030b fix gracefilly shutdown bug, issue #958 (#960) (AlphaBaby)
    • 1494fdc Fix clientGetURLDeadline (Erik Dubbelboer)
    • 0956208 Add request body streaming. Fixes #622 (#911) (Kirill Danshin)
    • fbe6a2d Add fasthttp.GenerateTestCertificate and use in tests (Erik Dubbelboer)
    • 838d3ab Allow concurrent ServeTLS (Erik Dubbelboer)
    • 3cec26d Allow stopping FS handler cleanup gorountine (#942) (Erik Dubbelboer)
    • ed1cedd Fix race condition in Client.DoTimeout (Erik Dubbelboer)
    • 5661df8 Improve documentation about DelClientCookie which related with #951. (#956) (kiyon)
    • b4b40e9 Do not start connsCleaner on SetConnectionClosed requests. (#950) (Mike Faraponov)
    • 70e00dc Ignore empty Transfer-Encoding headers (Erik Dubbelboer)
    Source code(tar.gz)
    Source code(zip)
  • v1.19.0(Jan 4, 2021)

    • 6234776 Use QueryString while constructing RequestURI instead of QueryArgs if parsedQueryArgs is set to false (#937) (anshul-jain-aws)
    • 245e7ec CloseIdleConnections should also close TLS connections (Erik Dubbelboer)
    • bd35133 Always set Keepalive options (Erik Dubbelboer)
    • 4e63057 Make argsKV more predictable (Erik Dubbelboer)
    Source code(tar.gz)
    Source code(zip)
  • v1.18.0(Dec 9, 2020)

    • d0dfbd4 fix issue #875 (#909) (Kirill Danshin)
    • ec4aa43 (header) do case insensitive lookup of cookie header value (#925) (Daniel Kürner)
    • f710c2d Fixing deletion of headers/queryargs having multiple values. (#918) (anshul-jain-aws)
    • cb0aaaa Improve round2 performance (#914) (kiyon)
    • c2542e5 add nil check for LocalAddr (#907) (Shohi Wang)
    • 30aa43e Adding Power support(ppc64le) with continuous integration/testing to the project for architecture independent (#903) (asellappen)
    • df87e70 Fix race condition in TestCloseIdleConnections (Erik Dubbelboer)
    Source code(tar.gz)
    Source code(zip)
  • v1.17.0(Nov 5, 2020)

    • 74bd13a Add ppc64le support (Erik Dubbelboer)
    • 00973e5 Don't use %w (Erik Dubbelboer)
    • d7752d2 fixed default schema for for req url (#897) (Maxim Korolyov)
    • ce7b94f Add Request.SetBodyRaw (Erik Dubbelboer)
    • d71fc6c Ignore *.fasthttp.br files from tests (Erik Dubbelboer)
    • 9697ccb Added httpproxy v2 (#889) (Maxim Korolyov)
    • 9ed328c remove unnecessary type conversion (#890) (Mohammad Alian)
    • 4eac1ae Added proxy from env support (#885) (Maxim Korolyov)
    • 56775f4 tryDial timeout (#881) (Vitali Pikulik)
    • 805af0e Brotli support in FS handler. (#880) (hex0x00)
    • ae8b65f Add Client.CloseIdleConnections() (Erik Dubbelboer)
    • aa3f96c Git commit fix URI parse for urls like host.dm?some/path/to/file (#866) (Vitali Pikulik)
    Source code(tar.gz)
    Source code(zip)
  • v1.16.0(Aug 17, 2020)

    • 434c48b Travis doesn't seem to support tip anymore (Erik Dubbelboer)
    • 12aba62 Change CI to use Go 1.15 (Erik Dubbelboer)
    • 01acd76 Allow TimeoutHandler connections to be kept alive (#864) (Erik Dubbelboer)
    • a995d43 Add EnableNormalizing to RequestHeader and ResponseHeader (Erik Dubbelboer)
    • cc8ba4b Add a api DisableNoDefaultContentType to disable add default content type. (#859) (sky)
    • 2509c12 improve statusLine and StatusMessage by using slice instead of map (#855) (kiyon)
    • a7c7ef2 Fix comment typo (So-chiru)
    • 34a61fe Update linting (#851) (Erik Dubbelboer)
    Source code(tar.gz)
    Source code(zip)
  • v1.15.1(Jul 15, 2020)

  • v1.15.0(Jul 14, 2020)

    • 607743c Ignore gosec warning in example (Erik Dubbelboer)
    • f97a382 Add letsencrypt example (Erik Dubbelboer)
    • e6ed19f update link to router package (#842) (Serge Romanov)
    • ef51a7e Fix fasthttpadaptor Content-Type detection (Erik Dubbelboer)
    • ac4cc17 Completely remove fuzzit (Erik Dubbelboer)
    • 38affcb Added Gearbox (#823) (Nagy Salem)
    • 9dd7979 Restart PipelineClient worker on error (#834) (Erik Dubbelboer)
    • 380f00b Fixed bug which prevents cached FS files from being updated (Erik Dubbelboer)
    • 2f28edb Fixed recompressing of stale files (Erik Dubbelboer)
    • 1671faf Prefork does work on windows (Erik Dubbelboer)
    • cc9db3a Try TravisCI Windows (#828) (Erik Dubbelboer)
    • ac51d59 Make the ErrNothingRead to be exposed. (#827) (sky)
    • 853abb3 🐞 panic in fs.go #824 (#825) (RW)
    • 33b3cb2 Support Windows SO_REUSEADDR (#822) (Andy Pan)
    • 29e6d09 Update TechEmpower benchmark from 18 to 19 round (#821) (Andy Pan)
    Source code(tar.gz)
    Source code(zip)
Owner
Aliaksandr Valialkin
Working on @VictoriaMetrics
Aliaksandr Valialkin
fhttp is a fork of net/http that provides an array of features pertaining to the fingerprint of the golang http client.

fhttp The f stands for flex. fhttp is a fork of net/http that provides an array of features pertaining to the fingerprint of the golang http client. T

Flexagon 61 Jan 1, 2023
A net.http.Handler similar to FileServer that serves gzipped content

net.http.handler.gzip: a FileServer that serves gzipped content. Usage: import "net/http/handler/gzip" base := "/path/to/website/static/files" http

Joao da Silva 15 Mar 14, 2022
An HTTP performance testing tool written in GoLang

Gonce A HTTP API performance testing tool written in GoLang Description Installation Usage Description A performance testing tool written in GoLang. S

Arham Jain 9 Jan 28, 2022
Gotcha is an high level HTTP client with a got-like API

Gotcha is an alternative to Go's http client, with an API inspired by got. It can interface with other HTTP packages through an adapter.

Sleeyax 20 Dec 7, 2022
Httpx - a fast and multi-purpose HTTP toolkit allow to run multiple probers using retryablehttp library

httpx is a fast and multi-purpose HTTP toolkit allow to run multiple probers using retryablehttp library, it is designed to maintain the result reliability with increased threads.

Will Pape 0 Feb 3, 2022
Replacement of ApacheBench(ab), support for transactional requests, support for command line and package references to HTTP stress testing tool.

stress stress is an HTTP stress testing tool. Through this tool, you can do a stress test on the HTTP service and get detailed test results. It is ins

Wenjia Xiong 37 Aug 23, 2022
fastcache is an HTTP response caching package that plugs into fastglue that simplifies

fastcache fastcache is a simple response caching package that plugs into fastglue. The Cached() middleware can be wrapped around fastglue GET handlers

Zerodha Technology 17 Apr 5, 2022
retryablehttp package provides a familiar HTTP client interface with automatic retries and exponential backoff.

retryablehttp package provides a familiar HTTP client interface with automatic retries and exponential backoff.

HashiCorp 1.4k Jan 4, 2023
Speak HTTP like a local. (the simple, intuitive HTTP console, golang version)

http-gonsole This is the Go port of the http-console. Speak HTTP like a local Talking to an HTTP server with curl can be fun, but most of the time it'

mattn 65 Jul 14, 2021
Http client call for golang http api calls

httpclient-call-go This library is used to make http calls to different API services Install Package go get

pzenteno 16 Oct 7, 2022
NATS HTTP Round Tripper - This is a Golang http.RoundTripper that uses NATS as a transport.

This is a Golang http.RoundTripper that uses NATS as a transport. Included is a http.RoundTripper for clients, a server that uses normal HTTP Handlers and any existing http handler mux and a Caddy Server transport.

R.I.Pienaar 81 Dec 6, 2022
Http-conection - A simple example of how to establish a HTTP connection using Golang

A simple example of how to establish a HTTP connection using Golang

Jonathan Gonzaga 0 Feb 1, 2022
goql is a GraphQL client package written in Go. with built-in two-way marshaling support via struct tags.

goql is a GraphQL client package written in Go. with built-in two-way marshaling support via struct tags.

Outreach 18 Dec 1, 2022
Full-featured, plugin-driven, extensible HTTP client toolkit for Go

gentleman Full-featured, plugin-driven, middleware-oriented toolkit to easily create rich, versatile and composable HTTP clients in Go. gentleman embr

Tom 986 Dec 23, 2022
An enhanced http client for Golang

go-http-client An enhanced http client for Golang Documentation on go.dev ?? This package provides you a http client package for your http requests. Y

Furkan Bozdag 51 Dec 23, 2022
An enhanced HTTP client for Go

Heimdall Description Installation Usage Making a simple GET request Creating a hystrix-like circuit breaker Creating a hystrix-like circuit breaker wi

Gojek 2.4k Jan 9, 2023
Enriches the standard go http client with retry functionality.

httpRetry Enriches the standard go http client with retry functionality using a wrapper around the Roundtripper interface. The advantage of this libra

Alexander Gehres 28 Dec 10, 2022
Go (golang) http calls with retries and backoff

pester pester wraps Go's standard lib http client to provide several options to increase resiliency in your request. If you experience poor network co

Seth Ammons 613 Dec 28, 2022
http client for golang

Request HTTP client for golang, Inspired by Javascript-axios Python-request. If you have experience about axios or requests, you will love it. No 3rd

Monaco.HappyHacking 223 Dec 18, 2022