dtnbjjq51949 2018-11-19 03:11 采纳率: 0%
浏览 505
已采纳

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

How can I force a simple Go client to use HTTP/2 and prevent it from falling back to HTTP 1.1 ?

I have a simple HTTP/2 server running on "localhost" and it returns details of the request in its reply. Here is the output using Google Chrome for this URL: https://localhost:40443/bananas

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

But here is what I get for my Go client code. You can see it falls back to HTTP 1.1

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

Below is the source code of my best attempt to contact the same server using HTTP/2, but it always falls back to 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:
%s", text)
}

Any suggestions would be appreciated, including pointers to other working examples that illustrate how to make HTTP/2 client requests in Go.

  • 写回答

1条回答 默认 最新

  • dream6120 2018-11-19 06:47
    关注

    First import "golang.org/x/net/http2" package. And then change

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

    to

    transport := &http2.Transport{TLSClientConfig: tlsConfig}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分