tss/proxy/proxy.go
2022-04-29 13:38:49 -04:00

48 lines
1.1 KiB
Go

package proxy
import (
"fmt"
"net/http"
"net/url"
"golang.org/x/net/proxy"
)
func GetClient(proxy string) (*http.Client, error) {
proxyUrl, err := url.Parse(proxy)
if err != nil {
return nil, fmt.Errorf("failed to parse proxyUrl, url:%s, err: %w", proxy, err)
}
if proxyUrl.Host == "unix" && proxyUrl.Scheme == "socks5" &&
len(proxyUrl.Path) > 1 /* Path cannot be empty or just / */ {
return unixSocks5Proxy(proxyUrl.Path)
}
return proxyHttp(proxyUrl)
}
func unixSocks5Proxy(path string) (*http.Client, error) {
// TODO: Auth?
dialer, err := proxy.SOCKS5("unix", path, nil /*auth*/, nil)
if err != nil {
return nil, fmt.Errorf("failed to make socks proxy, path: %s, err: %w", path, err)
}
ctxDialer, ok := dialer.(proxy.ContextDialer)
if !ok {
return nil, fmt.Errorf("proxy.SOCKS5 did not return a ContextDialer") // This should never happen
}
return &http.Client{
Transport: &http.Transport{
DialContext: ctxDialer.DialContext,
},
}, nil
}
func proxyHttp(proxyUrl *url.URL) (*http.Client, error) {
return &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyUrl),
},
}, nil
}