proxyClient.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package proxyClient
  2. import (
  3. "github.com/gogf/gf/v2/os/gcfg"
  4. "github.com/gogf/gf/v2/os/gctx"
  5. "net"
  6. "net/http"
  7. "net/http/httputil"
  8. "net/url"
  9. "strings"
  10. "time"
  11. )
  12. var transport = &http.Transport{}
  13. func CreateCustomProxyClient(target *url.URL, errFunc func(http.ResponseWriter, *http.Request, error)) *httputil.ReverseProxy {
  14. return &httputil.ReverseProxy{
  15. Director: func(req *http.Request) {
  16. targetQuery := target.RawQuery
  17. req.URL.Scheme = target.Scheme
  18. req.URL.Host = target.Host
  19. req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
  20. if targetQuery == "" || req.URL.RawQuery == "" {
  21. req.URL.RawQuery = targetQuery + req.URL.RawQuery
  22. } else {
  23. req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
  24. }
  25. if _, ok := req.Header["User-Agent"]; !ok {
  26. // explicitly disable User-Agent so it's not set to default value
  27. req.Header.Set("User-Agent", "")
  28. }
  29. },
  30. Transport: transport,
  31. //ModifyResponse: change,
  32. ErrorHandler: errFunc}
  33. }
  34. func ReLoadClient() {
  35. transport = &http.Transport{
  36. Proxy: http.ProxyFromEnvironment,
  37. DialContext: (&net.Dialer{
  38. Timeout: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.timeout", 30).Int()) * time.Second, //连接超时
  39. KeepAlive: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.keepAlive", 60).Int()) * time.Second, //长连接超时时间
  40. DualStack: true,
  41. }).DialContext,
  42. MaxIdleConns: gcfg.Instance().MustGet(gctx.New(), "proxy.maxIdleConns", 120).Int(), //最大空闲连接 0没有限制
  43. IdleConnTimeout: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.idleConnTimeout", 90).Int()) * time.Second, //空闲超时时间
  44. TLSHandshakeTimeout: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.tLSHandshakeTimeout", 1).Int()) * time.Second, //tls握手超时时间
  45. ExpectContinueTimeout: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.expectContinueTimeout", 1).Int()) * time.Second, //100-continue 超时时间
  46. MaxIdleConnsPerHost: gcfg.Instance().MustGet(gctx.New(), "proxy.maxIdleConnsPerHost", 5).Int(), //客户端可以持有的最大空闲连接
  47. }
  48. }
  49. func singleJoiningSlash(a, b string) string {
  50. aslash := strings.HasSuffix(a, "/")
  51. bslash := strings.HasPrefix(b, "/")
  52. switch {
  53. case aslash && bslash:
  54. return a + b[1:]
  55. case !aslash && !bslash:
  56. return a + "/" + b
  57. }
  58. return a + b
  59. }