Last active
March 3, 2020 06:20
-
-
Save acoshift/5b0094031317d10b0eb9fd95a1710377 to your computer and use it in GitHub Desktop.
http1 vs h2c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"crypto/tls" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"net" | |
"net/http" | |
"sync/atomic" | |
"time" | |
"golang.org/x/net/http2" | |
"golang.org/x/net/http2/h2c" | |
) | |
func main() { | |
srv := &http.Server{ | |
Addr: ":8080", | |
Handler: h2c.NewHandler( | |
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("OK")) | |
}), | |
&http2.Server{}, | |
), | |
} | |
go srv.ListenAndServe() | |
time.Sleep(100 * time.Millisecond) | |
var dialCnt uint64 | |
bench := func(name string, client *http.Client) { | |
dialCnt = 0 | |
var ( | |
okCnt uint64 | |
errCnt uint64 | |
) | |
request := func() { | |
resp, err := client.Get("http://127.0.0.1:8080") | |
if err != nil { | |
atomic.AddUint64(&errCnt, 1) | |
return | |
} | |
io.Copy(ioutil.Discard, resp.Body) | |
resp.Body.Close() | |
atomic.AddUint64(&okCnt, 1) | |
} | |
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) | |
for i := 0; i < 8; i++ { | |
go func() { | |
for j := 0; j < 200; j++ { | |
go func() { | |
for { | |
select { | |
case <-ctx.Done(): | |
return | |
default: | |
request() | |
} | |
} | |
}() | |
} | |
}() | |
} | |
<-ctx.Done() | |
fmt.Printf("%s\ndial: %d times\nok: %d req/s\nerr: %d total\n", name, dialCnt, okCnt/10, errCnt) | |
} | |
bench("http1", &http.Client{ | |
Transport: &http.Transport{ | |
DialContext: func(ctx context.Context, network, addr string) (conn net.Conn, err error) { | |
atomic.AddUint64(&dialCnt, 1) | |
return net.Dial(network, addr) | |
}, | |
DisableCompression: true, | |
MaxIdleConnsPerHost: 200, | |
}, | |
}) | |
bench("h2c", &http.Client{ | |
Transport: &http2.Transport{ | |
DialTLS: func(network, addr string, cfg *tls.Config) (conn net.Conn, err error) { | |
atomic.AddUint64(&dialCnt, 1) | |
return net.Dial(network, addr) | |
}, | |
DisableCompression: true, | |
AllowHTTP: true, | |
}, | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment