如何在Go中从http客户端获取x509证书
问题描述:
I've been over the docs at https://golang.org/pkg/ but can't make this connection.
I am creating a client and request like so (error handling removed):
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)
I need to get a x509.Certificate
to read details of the cert returned from the server, but still need the http.Repsonse
as well.
How can I get a x509.Certificate
instance and an http.Response
while only making a single request?
我浏览过 https://golang.org/pkg/ 但无法建立此连接。 p>
我正在创建客户端,并像这样请求( 错误处理已删除): p>
client:= http.Client {
CheckRedirect:func(req * http.Request,通过[] * http.Request)错误{
返回http.ErrUseLastResponse
},
}
req,reqErr:= http.NewRequest(requestMethod,requestUrl,nil)
resp,clientErr:= client.Do(req)
code> pre> \ n
我需要获取一个 x509.Certificate code>来读取从服务器返回的证书的详细信息,但仍然还需要 http.Repsonse code>。 / p>
如何仅通过单个请求获取 x509.Certificate code>实例和 http.Response code>? p> \ n div>
答
The response has a TLS *tls.ConnectionState
field, which in turn has:
type ConnectionState struct {
// other fields
PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
}
so you can just do:
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]
}
}