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

How to force client to use http/2? (instead of falling back to http 1.1)

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

我在 "localhost" 上有一个简单的 HTTP/2 服务器 运行,它在回复中 returns 请求的详细信息。这是使用 Google Chrome 的输出 URL:https://localhost:40443/bananas

I like bananas!
Method       = GET
URL          = /bananas
Proto        = HTTP/2.0
Host         = localhost:40443
RequestURI   = /bananas

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

I like monkeys!
Method       = GET
URL          = /monkeys
Proto        = HTTP/1.1
Host         = localhost:40443
RequestURI   = /monkeys

以下是我使用 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)
}

任何建议,包括指向说明如何在 Go 中发出 HTTP/2 客户端请求的其他工作示例的指针,我们将不胜感激。

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

transport := &http.Transport{TLSClientConfig: tlsConfig}

transport := &http2.Transport{TLSClientConfig: tlsConfig}