如何强制客户端使用http/2?(而不是回归到http1.1)

5
我该如何让一个简单的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

但是这是我在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客户端请求,将不胜感激。


可能存在类似问题 https://github.com/golang/go/issues/14391 - novalagung
1个回答

7

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

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

为了

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

1
如果HTTP/2能够像某些文档所建议的那样被透明地支持,那将是很好的,但似乎一旦您开始添加配置选项,您就会失去这种透明性,并且需要明确引用HTTP2。 - David Jones
在Java的Web服务器中,我们如何实现相同的功能(强制客户端使用http2)? - Aryan Venkat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接