12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- package proxyClient
- import (
- "github.com/gogf/gf/v2/os/gcfg"
- "github.com/gogf/gf/v2/os/gctx"
- "net"
- "net/http"
- "net/http/httputil"
- "net/url"
- "strings"
- "time"
- )
- var transport = &http.Transport{}
- func CreateCustomProxyClient(target *url.URL, errFunc func(http.ResponseWriter, *http.Request, error)) *httputil.ReverseProxy {
- return &httputil.ReverseProxy{
- Director: func(req *http.Request) {
- targetQuery := target.RawQuery
- req.URL.Scheme = target.Scheme
- req.URL.Host = target.Host
- req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
- if targetQuery == "" || req.URL.RawQuery == "" {
- req.URL.RawQuery = targetQuery + req.URL.RawQuery
- } else {
- req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
- }
- if _, ok := req.Header["User-Agent"]; !ok {
- // explicitly disable User-Agent so it's not set to default value
- req.Header.Set("User-Agent", "")
- }
- },
- Transport: transport,
- //ModifyResponse: change,
- ErrorHandler: errFunc}
- }
- func ReLoadClient() {
- transport = &http.Transport{
- Proxy: http.ProxyFromEnvironment,
- DialContext: (&net.Dialer{
- Timeout: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.timeout", 30).Int()) * time.Second, //连接超时
- KeepAlive: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.keepAlive", 60).Int()) * time.Second, //长连接超时时间
- DualStack: true,
- }).DialContext,
- MaxIdleConns: gcfg.Instance().MustGet(gctx.New(), "proxy.maxIdleConns", 120).Int(), //最大空闲连接 0没有限制
- IdleConnTimeout: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.idleConnTimeout", 90).Int()) * time.Second, //空闲超时时间
- TLSHandshakeTimeout: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.tLSHandshakeTimeout", 1).Int()) * time.Second, //tls握手超时时间
- ExpectContinueTimeout: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.expectContinueTimeout", 1).Int()) * time.Second, //100-continue 超时时间
- MaxIdleConnsPerHost: gcfg.Instance().MustGet(gctx.New(), "proxy.maxIdleConnsPerHost", 5).Int(), //客户端可以持有的最大空闲连接
- }
- }
- func singleJoiningSlash(a, b string) string {
- aslash := strings.HasSuffix(a, "/")
- bslash := strings.HasPrefix(b, "/")
- switch {
- case aslash && bslash:
- return a + b[1:]
- case !aslash && !bslash:
- return a + "/" + b
- }
- return a + b
- }
|