proxyClient.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package proxyClient
  2. import (
  3. "bp.jydev.jianyu360.cn/BaseService/gateway/core/util"
  4. "context"
  5. "github.com/gogf/gf/v2/os/gcfg"
  6. "github.com/gogf/gf/v2/os/gctx"
  7. "net"
  8. "net/http"
  9. "net/http/httputil"
  10. "net/url"
  11. "time"
  12. )
  13. var transport = &http.Transport{}
  14. func CreateCustomProxyClient(target *url.URL, errFunc func(http.ResponseWriter, *http.Request, error), change func(resp *http.Response) error) *httputil.ReverseProxy {
  15. return &httputil.ReverseProxy{
  16. Director: func(req *http.Request) {
  17. req.URL.Scheme = target.Scheme
  18. req.URL.Host = target.Host
  19. req.URL.Path = util.SingleJoiningSlash(target.Path, req.URL.Path)
  20. },
  21. Transport: transport,
  22. ModifyResponse: change,
  23. ErrorHandler: errFunc}
  24. }
  25. func ReLoadClient() {
  26. transport = &http.Transport{
  27. Proxy: http.ProxyFromEnvironment,
  28. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  29. dialer := &net.Dialer{
  30. Timeout: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.timeout", 30).Int()) * time.Second, //连接超时
  31. KeepAlive: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.keepAlive", 60).Int()) * time.Second, //长连接超时时间
  32. }
  33. return dialer.DialContext(ctx, network, addr)
  34. },
  35. MaxIdleConns: gcfg.Instance().MustGet(gctx.New(), "proxy.maxIdleConns", 120).Int(), //最大空闲连接 0没有限制
  36. IdleConnTimeout: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.idleConnTimeout", 90).Int()) * time.Second, //空闲超时时间
  37. TLSHandshakeTimeout: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.tLSHandshakeTimeout", 1).Int()) * time.Second, //tls握手超时时间
  38. ExpectContinueTimeout: time.Duration(gcfg.Instance().MustGet(gctx.New(), "proxy.expectContinueTimeout", 1).Int()) * time.Second, //100-continue 超时时间
  39. MaxIdleConnsPerHost: gcfg.Instance().MustGet(gctx.New(), "proxy.maxIdleConnsPerHost", 5).Int(), //客户端可以持有的最大空闲连接
  40. DisableKeepAlives: gcfg.Instance().MustGet(gctx.New(), "proxy.disableKeepAlives", false).Bool(),
  41. }
  42. }