在How to consume a REST API in Go中,提供了fully working example code来调用公共REST API.但是,如果我try 该示例,则会出现以下错误:
error getting cat fact:
Get "https://catfact.ninja/fact":
proxyconnect tcp: tls: first record does not look like a TLS handshake
要控制代理、TLS配置、保持连接、压缩和其他设置,请创建传输:
// DialContext specifies the dial function for creating unencrypted TCP connections.
// If DialContext is nil (and the deprecated Dial below is also nil),
// then the transport dials using package net.
//
// DialContext runs concurrently with calls to RoundTrip.
// A RoundTrip call that initiates a dial may end up using
// a connection dialed previously when the earlier connection
// becomes idle before the later DialContext completes.
DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
因此,我假设我必须配置拨号上下文以启用从我的客户端到代理的不安全连接without TLS
.但我不知道该怎么做.阅读这些内容:
- How to do proxy and TLS in golang个;
- How to HTTP/HTTPS GET via Proxy个;以及
- How to do a https request with bad certificate?个
也没有起到任何作用.一些人有相同的错误proxyconnect tcp: tls: first record does not look like a TLS handshake
并解释了原因:
这是因为代理对奇怪的HTTP请求(实际上是TLS握手的开始)的响应是一个简单的HTTP错误.
但是Steffen's reply没有示例代码如何设置DialContext func(ctx context.Context, network, addr string)
,Bogdan和cyberdelia都建议这样设置tls.Config{InsecureSkipVerify: true}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
但上述措施并未奏效.我仍然收到相同的错误.而且连接仍在呼叫https://*
,而不是http://*
这是样例代码,我try 包含上述建议并对其进行修改:
var tr = &http.Transport{ TLSClientConfig:
&tls.Config{InsecureSkipVerify: true}, }
// lacks DialContext config
var client* http.Client = &http.Client{Transport: tr} // modified * added
// var client *http.Client // code from tutorial
type CatFact struct {
Fact string `json:"fact"`
Length int `json:"length"`
}
func GetCatFact() {
url := "http://catfact.ninja/fact" // changed from https to http
var catFact CatFact
err := GetJson(url, &catFact)
if err != nil {
fmt.Printf("error getting cat fact: %s\n", err.Error())
} else {
fmt.Printf("A super interesting Cat Fact: %s\n", catFact.Fact)
}
}
func main() {
client = &http.Client{Timeout: 10 * time.Second}
GetCatFact()
// same error
// proxyconnect tcp: tls: first record does
// not look like a TLS handshake
// still uses https
// for GET catfact.ninja
}
如何将连接配置为使用从myClient通过代理到服务器的未加密连接?设定DialContext func(ctx context.Context, network, addr string)
会有助于做到这一点吗?如何做到这一点呢?