gpt4 book ai didi

go - 响应后验证证书

转载 作者:IT王子 更新时间:2023-10-29 01:58:47 25 4
gpt4 key购买 nike

我想连接到可能不安全的主机,所以我使用 http.Client 像这样:

client := &http.Client{
Timeout: timeout,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
resp, err := client.Get(url)

效果很好,但我似乎找不到事后检查 SSL 证书有效性的方法。我意识到我可以建立两个连接(一个使用 InsecureSkipVerify,一个不使用),但我想这样做而不建立另一个连接。

最佳答案

可行。 =)

您应该在 Transport 上设置 Dial 和 DialTLS 字段并在那里进行检查。

希望代码是不言自明的,欢迎随时提问。

由于限制,不能在 Playground 上工作!

https://play.golang.org/p/4TkczUEnKn

package main

import (
"fmt"
"net/http"
"net"
"time"
"crypto/tls"
)

func DialTLS(network, addr string) (net.Conn, error) {
conn, err := tls.Dial(network, addr, &tls.Config{
InsecureSkipVerify: true,
})

cs := conn.ConnectionState()
fmt.Println(cs.Version, cs.HandshakeComplete)
// insert your check here!

return conn, err
}

func Dial (network, addr string) (net.Conn, error) {
// Copied from DefaultTransport
dialer := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
conn, err := dialer.Dial(network, addr)

fmt.Println("unsecure")

return conn, err
}

func main() {
client := &http.Client{
Timeout: time.Second,
Transport: &http.Transport{
Dial: Dial,

// If DialTLS is set, the Dial hook is not used for HTTPS
// requests and the TLSClientConfig and TLSHandshakeTimeout
// are ignored. The returned net.Conn is assumed to already be
// past the TLS handshake.

// TLSClientConfig: &tls.Config{
// InsecureSkipVerify: true,
// },
DialTLS: DialTLS,
},
}

// Deep in transport it checks "tlsDial := t.DialTLS != nil && cm.targetScheme == "https" && cm.proxyURL == nil"
// https://golang.org/src/net/http/transport.go#L741
resp, err := client.Get("https://www.google.com")
fmt.Println(resp, err, "\n\n")

resp , err = client.Get("http://www.google.com")
fmt.Println(resp, err)
}

UPD

UPD2:下面的代码是个坏主意 =)。后备逻辑混淆了 http.Client error = Get https://www.google.com: http: server gave HTTP response to HTTPS client 或者我遗漏了什么,好吧,现在由你决定 =)

甚至更好(取决于您的逻辑)。

func DialTLSWithFallback(network, addr string) (net.Conn, error) {
conn, err := tls.Dial(network, addr, &tls.Config{
InsecureSkipVerify: true,
})

if err != nil {
// obviously, usecure
// lets try net.Dial
// and return, so check bellow wont trigger on wrong connection type
return &(net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial(network, addr)
}

cs := conn.ConnectionState()
fmt.Println(cs.Version, cs.HandshakeComplete)
// its "secure" connection
// check is it strong enough here!

return conn, err
}

然后你把收缩物运输到

        Transport: &http.Transport{
Dial: DialTLSWithFallback,
DialTLS: DialTLSWithFallback,
}

关于go - 响应后验证证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37733187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com