Last active
December 14, 2023 12:33
-
-
Save niksteff/7d39c6f674a7bf98d71ad2c3add68f94 to your computer and use it in GitHub Desktop.
Testing golang http2 client and server
This file contains 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 http2_test | |
import ( | |
"crypto/tls" | |
"crypto/x509" | |
"net/http" | |
"net/http/httptest" | |
"testing" | |
"time" | |
"golang.org/x/net/http2" | |
) | |
func getMux(t *testing.T) *http.ServeMux { | |
// define our http handler | |
mux := http.NewServeMux() | |
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
t.Logf("received request: %+v", r) | |
w.WriteHeader(http.StatusOK) | |
_, _ = w.Write([]byte("foo bar!")) | |
}) | |
return mux | |
} | |
func TestMakeHTTPConnection(t *testing.T) { | |
// start an http1.1 server | |
srv := httptest.NewUnstartedServer(getMux(t)) | |
srv.EnableHTTP2 = false | |
srv.Start() | |
defer srv.Close() | |
// create a http1.1 client | |
transport := http.DefaultTransport.(*http.Transport).Clone() | |
httpClient := http.DefaultClient | |
httpClient.Transport = transport | |
// perform http1 request | |
_, err := httpClient.Get(srv.URL) | |
if err != nil { | |
t.Errorf("error while performing http1 request: %s", err.Error()) | |
} | |
} | |
func TestMakeHTTP2Connection(t *testing.T) { | |
// start an http2 server | |
srv := httptest.NewUnstartedServer(getMux(t)) | |
srv.EnableHTTP2 = true | |
srv.StartTLS() | |
defer srv.Close() | |
transport := http.DefaultTransport.(*http.Transport).Clone() | |
// trust the servers tls cert | |
certpool := x509.NewCertPool() | |
certpool.AddCert(srv.Certificate()) | |
tlsconf := &tls.Config{RootCAs: certpool} | |
transport.TLSClientConfig = tlsconf | |
h2Transport, err := http2.ConfigureTransports(transport) | |
if err != nil { | |
t.Errorf("error while configuring http2 transport: %s", err.Error()) | |
return | |
} | |
h2Transport.ReadIdleTimeout = time.Second * 1 // ping is performed at N whenever no frame was received in the meantime | |
h2Transport.PingTimeout = time.Second * 3 // after what time a ping is considered timed out | |
http2Client := http.DefaultClient | |
http2Client.Transport = transport | |
// perform http2 request | |
_, err = http2Client.Get(srv.URL) | |
if err != nil { | |
t.Errorf("error while performing http2 request: %s", err.Error()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please make sure that for a self signed server certificate, like in this example, you have to configure the
TLSClientConfig
before you callhttp2.ConfigureTransports(...)
and thus upgrading your http1.1 connection to http2. Otherwise you will receive a connection pool error but it really should be a cert error from golang's side. This is rather unlucky.