如何强制客户端使用http/2?(而不是回退到 http 1.1)

Dav*_*nes 6 https client go http2

如何强制简单的 Go 客户端使用 HTTP/2 并防止其回退到 HTTP 1.1 ?

我有一个在“localhost”上运行的简单 HTTP/2 服务器,它在回复中返回请求的详细信息。以下是使用 Google Chrome 访问此 URL 的输出:https://localhost:40443/bananas

I like bananas!
Method       = GET
URL          = /bananas
Proto        = HTTP/2.0
Host         = localhost:40443
RequestURI   = /bananas
Run Code Online (Sandbox Code Playgroud)

但这是我得到的 Go 客户端代码。您可以看到它回落到 HTTP 1.1

I like monkeys!
Method       = GET
URL          = /monkeys
Proto        = HTTP/1.1
Host         = localhost:40443
RequestURI   = /monkeys
Run Code Online (Sandbox Code Playgroud)

下面是我尝试使用 HTTP/2 联系同一服务器的源代码,但它总是回落到 HTTP 1.1

// simple http/2 client

package main

import (
    "crypto/tls"
    "crypto/x509"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

const (
    certFile = "client-cert.pem"
    keyFile  = "client-key.pem"
    caFile   = "server-cert.pem"
)

func main() {
    // Load client certificate
    cert, err := tls.LoadX509KeyPair(certFile, keyFile)
    if err != nil {
        log.Fatal(err)
    }

    // Load CA cert
    caCert, err := ioutil.ReadFile(caFile)
    if err != nil {
        log.Fatal(err)
    }
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    // Setup HTTPS client
    tlsConfig := &tls.Config{
        Certificates: []tls.Certificate{cert},
        RootCAs:      caCertPool,
    }
    tlsConfig.BuildNameToCertificate()
    transport := &http.Transport{TLSClientConfig: tlsConfig}
    client := &http.Client{Transport: transport}

    response, err := client.Get("https://localhost:40443/monkeys")
    if err != nil {
        log.Fatal(err)
    }
    defer response.Body.Close()

    // dump response
    text, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Body:\n%s", text)
}
Run Code Online (Sandbox Code Playgroud)

任何建议都将受到赞赏,包括指向其他​​工作示例的指针,这些示例说明了如何在 Go 中发出 HTTP/2 客户端请求。

Shu*_*rma 10

首先导入"golang.org/x/net/http2"包。然后改变

transport := &http.Transport{TLSClientConfig: tlsConfig}
Run Code Online (Sandbox Code Playgroud)

transport := &http2.Transport{TLSClientConfig: tlsConfig}
Run Code Online (Sandbox Code Playgroud)