我正在使用核心网/http/httputil/ReverseProxy库在Go中编写反向代理服务器。我已经使用了一个自定义的主管,我需要为传输定义我自己的RoundTrip和拨号。
我可以像这样使用定制拨号:
transport := &http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
lgr.Println("running custom magic below")
// custom magic
return net.Dial(network, addr)
},
}
res := &httputil.ReverseProxy{Director: director, Transport: transport}
return res因此,我创建了一个自定义传输,它嵌入了这样的http.Transport:
type customTransport struct {
http.Transport
}
func (t *customTransport) RoundTrip(req *http.Request) (*http.Response, error) {
res, err := http.DefaultTransport.RoundTrip(req)
lgr.Println("checking the response")
// check the response
return res, err
}我试着用它来代替默认的传输方式:
transport := &customTransport{http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
lgr.Println("running custom magic below")
// custom magic
return net.Dial(network, addr)
},
}}
res := &httputil.ReverseProxy{Director: director, Transport: transport}问题是,虽然我的自定义RoundTrip工作良好,但拨号现在停止工作,不再做定制魔术。
当我在分配transport.Dial之后立即记录它的地址时,我会在内存中看到它的地址。当我记录我的RevereProxy.Transport (上面的函数在res中返回)时,我甚至在那里看到相同的地址:
fmt.Printf("%#v", transport.Dial)
2016/02/18 12:11:48.401245 main.go:76: (func(string, string) (net.Conn, error))(0x4039a0)
fmt.Printf("%#v", proxy.Transport)
2016/02/18 12:11:48.401403 main.go:100: &main.customTransport{Transport:http.Transport{idleMu:sync.Mutex{state:0, sema:0x0}, wantIdle:false, idleConn:map[http.connectMethodKey][]*http.persistConn(nil), idleConnCh:map[http.connectMethodKey]chan *http.persistConn(nil), reqMu:sync.Mutex{state:0, sema:0x0}, reqCanceler:map[*http.Request]func()(nil), altMu:sync.RWMutex{w:sync.Mutex{state:0, sema:0x0}, writerSem:0x0, readerSem:0x0, readerCount:0, readerWait:0}, altProto:map[string]http.RoundTripper(nil), Proxy:(func(*http.Request) (*url.URL, error))(nil), Dial:(func(string, string) (net.Conn, error))(0x4039a0), DialTLS:(func(string, string) (net.Conn, error))(nil), TLSClientConfig:(*tls.Config)(nil), TLSHandshakeTimeout:0, DisableKeepAlives:false, DisableCompression:false, MaxIdleConnsPerHost:0, ResponseHeaderTimeout:0, ExpectContinueTimeout:0, TLSNextProto:map[string]func(string, *tls.Conn) http.RoundTripper(nil), nextProtoOnce:sync.Once{m:sync.Mutex{state:0, sema:0x0}, done:0x0}, h2transport:(*http.http2Transport)(nil)}}无论如何,核心的net.Dial方法似乎被调用,而不是我的自定义拨号,我真的不知道为什么。谢谢!
发布于 2016-02-18 16:49:08
您正在定义一个自定义传输,但在RoundTrip上调用http.DefaultTransport。您需要在嵌入式传输上调用RoundTrip:
type customTransport struct {
*http.Transport
}
func (t *customTransport) RoundTrip(req *http.Request) (*http.Response, error) {
res, err := t.Transport.RoundTrip(req)
lgr.Println("checking the response")
// check the response
return res, err
}发布于 2022-03-10 21:14:33
无需自定义Dial,只需在TLSClientConfig中设置InsecureSkipVerify选项
proxy.Transport = &customTransport{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}https://stackoverflow.com/questions/35480455
复制相似问题