【发布时间】:2019-04-21 09:50:34
【问题描述】:
如何强制简单的 Go 客户端使用 HTTP/2 并防止它回退到 HTTP 1.1?
我有一个在“localhost”上运行的简单 HTTP/2 服务器,它在回复中返回请求的详细信息。这是使用谷歌浏览器对该 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 客户端请求。
【问题讨论】: