-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproxy.go
67 lines (55 loc) · 1.6 KB
/
proxy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package requests
import (
"fmt"
"net/http"
"net/url"
)
// verifyProxy validates the given proxy URL, supporting http, https, and socks5 schemes.
func verifyProxy(proxyURL string) (*url.URL, error) {
parsedURL, err := url.Parse(proxyURL)
if err != nil {
return nil, err
}
// Check if the scheme is supported
switch parsedURL.Scheme {
case "http", "https", "socks5":
return parsedURL, nil
default:
return nil, fmt.Errorf("%w: %s", ErrUnsupportedScheme, parsedURL.Scheme)
}
}
// SetProxy configures the client to use a proxy. Supports http, https, and socks5 proxies.
func (c *Client) SetProxy(proxyURL string) error {
c.mu.Lock()
defer c.mu.Unlock()
// Validate and parse the proxy URL
validatedProxyURL, err := verifyProxy(proxyURL)
if err != nil {
return err
}
// Ensure the HTTPClient's Transport is properly initialized
if c.HTTPClient.Transport == nil {
c.HTTPClient.Transport = &http.Transport{}
}
// Assert the Transport to *http.Transport to access the Proxy field
transport, ok := c.HTTPClient.Transport.(*http.Transport)
if !ok {
return fmt.Errorf("%w: expected *http.Transport, got %T", ErrInvalidTransportType, c.HTTPClient.Transport)
}
// Set the proxy
transport.Proxy = http.ProxyURL(validatedProxyURL)
return nil
}
// RemoveProxy clears any configured proxy, allowing direct connections.
func (c *Client) RemoveProxy() {
c.mu.Lock()
defer c.mu.Unlock()
if c.HTTPClient.Transport == nil {
return
}
transport, ok := c.HTTPClient.Transport.(*http.Transport)
if !ok {
return // If it's not *http.Transport, it doesn't have a proxy to remove
}
transport.Proxy = nil
}