所以我试图使用httptest.TLSServer
模拟对https请求的响应,但http.Client
发出请求时告诉我服务器正在提供无效的http响应。我打赌这是因为没有真正的SSL证书。有什么方法可以让客户端忽略tls而仍然嘲笑https请求吗?
有问题的测试代码
func TestFacebookLogin(t *testing.T) {
db := glob.db
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
resp := `
{
"id": "123",
"email": "blah",
"first_name": "Ben",
"last_name": "Botwin"
}
`
w.Write([]byte(resp))
}))
defer server.Close()
transport := &http.Transport{
Proxy: func(r *http.Request) (*url.URL, error) {
return url.Parse(server.URL)
},
}
svc := userService{db: db, client: &http.Client{Transport: transport}}
_, err := svc.FacebookLogin("asdf")
if err != nil {
t.Errorf("Error found: %s", err)
}
}
我要做的请求:
url := "https://<Some facebook api endpoint>"
req, err := http.NewRequest("GET", url, nil)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
答案 0 :(得分:4)
测试服务器使用自签名证书。有两种方法可以避免错误。第一种是使用配置了test server's certificates:
的HTTP客户端certs := x509.NewCertPool()
for _, c := range server.TLS.Certificates {
roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
if err != nil {
log.Fatalf("error parsing server's root cert: %v", err)
}
for _, root := range roots {
certs.AddCert(root)
}
}
client := http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: certs,
},
},
}
更简单的选择是跳过证书验证:
client := http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
还有一个问题。客户端期望连接到代理服务器,但它实际上直接连接到测试服务器。尝试挂钩拨号功能而不是代理:
client := http.Client{
Transport: &http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
return net.Dial("tcp", server.URL[strings.LastIndex(server.URL, "/")+1:])
},
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}