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

时间:2019-02-28 17:01:18

标签: go

我已经浏览过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

1 个答案:

答案 0 :(得分:3)

响应包含一个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] 
    }
}