登录
首页 >  Golang >  Go问答

如何确保客户端在使用http时不降级到http 1.1?

来源:stackoverflow

时间:2024-03-10 09:27:25 184浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《如何确保客户端在使用http时不降级到http 1.1?》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

如何强制简单的 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 客户端请求。


解决方案


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

transport := &http.transport{tlsclientconfig: tlsconfig}

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

终于介绍完啦!小伙伴们,这篇关于《如何确保客户端在使用http时不降级到http 1.1?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>