Last active
July 30, 2024 22:12
-
-
Save wolfeidau/230eda73402392052523a6cacd691393 to your computer and use it in GitHub Desktop.
Allow disabling of HTTP/2.0 while using the optimal default configuration in Go
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 main | |
import ( | |
"crypto/tls" | |
"flag" | |
"log/slog" | |
"net/http" | |
"os" | |
) | |
var disableHTTP2 = flag.Bool("disable-http2", false, "Disable HTTP/2.0") | |
func main() { | |
flag.Parse() | |
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{}))) | |
tr := http.DefaultTransport.(*http.Transport).Clone() | |
if *disableHTTP2 { | |
tr.ForceAttemptHTTP2 = false | |
tr.TLSNextProto = make(map[string]func(authority string, c *tls.Conn) http.RoundTripper) | |
// The default TLSClientConfig has h2 in NextProtos, so the negotiated TLS connection will assume h2 support. | |
// see https://github.com/golang/go/issues/50571 | |
tr.TLSClientConfig = &tls.Config{} | |
} | |
client := http.Client{ | |
Transport: tr, | |
} | |
resp, err := client.Get("https://google.com") | |
if err != nil { | |
panic(err) | |
} | |
defer resp.Body.Close() | |
// Print the HTTP Status Code | |
slog.With("resp.Status", resp.Status, "resp.StatusCode", resp.StatusCode, "resp.Proto", resp.Proto).Info("HTTP Status Code") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment