feat: 完善代理池与抢购链路,发布 0.5.0
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// MonitorProxyHealth 为代理客户端安装传输层健康回调。
|
||||
// 回调参数为 nil 表示一次完整传输成功;非 nil 表示连接、超时或响应体读取失败。
|
||||
func MonitorProxyHealth(c *DouyuClient, handler func(error)) {
|
||||
if c == nil || c.HTTPClient == nil || handler == nil {
|
||||
return
|
||||
}
|
||||
if _, ok := c.HTTPClient.Transport.(*proxyHealthTransport); ok {
|
||||
return
|
||||
}
|
||||
base := c.HTTPClient.Transport
|
||||
if base == nil {
|
||||
base = http.DefaultTransport
|
||||
}
|
||||
c.HTTPClient.Transport = &proxyHealthTransport{
|
||||
base: base,
|
||||
handler: handler,
|
||||
}
|
||||
}
|
||||
|
||||
// IsProxyTransportFailure 区分真实网络故障与主动取消。
|
||||
func IsProxyTransportFailure(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
return !errors.Is(err, context.Canceled)
|
||||
}
|
||||
|
||||
type proxyHealthTransport struct {
|
||||
base http.RoundTripper
|
||||
handler func(error)
|
||||
}
|
||||
|
||||
func (t *proxyHealthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
resp, err := t.base.RoundTrip(req)
|
||||
if err != nil {
|
||||
if IsProxyTransportFailure(err) {
|
||||
t.handler(err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
t.handler(nil)
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body = &proxyHealthBody{
|
||||
ReadCloser: resp.Body,
|
||||
handler: t.handler,
|
||||
}
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (t *proxyHealthTransport) CloseIdleConnections() {
|
||||
if closer, ok := t.base.(interface{ CloseIdleConnections() }); ok {
|
||||
closer.CloseIdleConnections()
|
||||
}
|
||||
}
|
||||
|
||||
type proxyHealthBody struct {
|
||||
io.ReadCloser
|
||||
once sync.Once
|
||||
handler func(error)
|
||||
}
|
||||
|
||||
func (b *proxyHealthBody) Read(p []byte) (int, error) {
|
||||
n, err := b.ReadCloser.Read(p)
|
||||
if err != nil && !errors.Is(err, io.EOF) && IsProxyTransportFailure(err) {
|
||||
b.once.Do(func() {
|
||||
b.handler(err)
|
||||
})
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
Reference in New Issue
Block a user