登录
首页 >  Golang >  Go问答

如何在 Go 中从 http 客户端获取 x509 证书

来源:stackoverflow

时间:2024-04-10 12:21:33 148浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《如何在 Go 中从 http 客户端获取 x509 证书》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我已经阅读了 https://golang.org/pkg/ 上的文档,但无法建立此连接。

我正在创建一个客户端并像这样请求(错误处理已删除):

client := http.Client{
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
        return http.ErrUseLastResponse
    },
}
req, reqErr := http.NewRequest(requestMethod, requestUrl, nil)
resp, clientErr := client.Do(req)

我需要获取 x509.certificate 来读取从服务器返回的证书的详细信息,但仍然需要 http.repsonse

如何在仅发出单个请求的情况下获取 x509.certificate 实例和 http.response


解决方案


响应有一个 tls *tls.connectionstate 字段,该字段又包含:

type connectionstate struct {
    // other fields
    peercertificates []*x509.certificate   // certificate chain presented by remote peer
}

所以你可以这样做:

resp, clientErr := client.Do(req)
if clientErr != nil {
    panic(clientErr)
}
if resp.TLS != nil {
    certificates := resp.TLS.PeerCertificates
    if len(certificates) > 0 {
        // you probably want certificates[0]
        cert := certificates[0] 
    }
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

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