Procházet zdrojové kódy

[🚀] 添加Proxy

bvbej před 9 měsíci
rodič
revize
7389825836

+ 13 - 0
pkg/downloader/controller/controller.go

@@ -4,6 +4,7 @@ import (
 	"golang.org/x/net/proxy"
 	"net"
 	"net/http"
+	"net/url"
 	"os"
 	"time"
 )
@@ -16,6 +17,7 @@ type Controller interface {
 	ContextDialer() (proxy.Dialer, error)
 	ContextCookie() http.CookieJar
 	ContextTimeout() time.Duration
+	ContextProxy() func(*http.Request) (*url.URL, error)
 }
 
 type Option func(*option)
@@ -24,6 +26,7 @@ type option struct {
 	CookieJar http.CookieJar
 	Timeout   time.Duration
 	Dialer    proxy.Dialer
+	Proxy     func(*http.Request) (*url.URL, error)
 }
 
 func WithCookie(cookieJar http.CookieJar) Option {
@@ -44,6 +47,12 @@ func WithDialer(dialer proxy.Dialer) Option {
 	}
 }
 
+func WithProxy(fn func(*http.Request) (*url.URL, error)) Option {
+	return func(opt *option) {
+		opt.Proxy = fn
+	}
+}
+
 type DefaultController struct {
 	*option
 	Files map[string]*os.File
@@ -110,6 +119,10 @@ func (c *DefaultController) ContextTimeout() time.Duration {
 	return c.Timeout
 }
 
+func (c *DefaultController) ContextProxy() func(*http.Request) (*url.URL, error) {
+	return c.Proxy
+}
+
 type DialerWarp struct {
 	dialer proxy.Dialer
 }

+ 3 - 0
pkg/downloader/protocol/http/fetcher.go

@@ -357,6 +357,9 @@ func (f *Fetcher) buildClient() (*http.Client, error) {
 			return dialer.Dial(network, addr)
 		},
 	}
+	if f.Ctl.ContextProxy() != nil {
+		transport.Proxy = f.Ctl.ContextProxy()
+	}
 	return &http.Client{
 		Jar:       f.Ctl.ContextCookie(),
 		Timeout:   f.Ctl.ContextTimeout(),