proxyClient.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package proxy
  2. import (
  3. "net"
  4. "net/http"
  5. "net/http/httputil"
  6. "net/url"
  7. "strings"
  8. "time"
  9. )
  10. func CreateCustomProxyClient(target *url.URL, errFunc func(http.ResponseWriter, *http.Request, error)) *httputil.ReverseProxy {
  11. director := func(req *http.Request) {
  12. targetQuery := target.RawQuery
  13. req.URL.Scheme = target.Scheme
  14. req.URL.Host = target.Host
  15. req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
  16. if targetQuery == "" || req.URL.RawQuery == "" {
  17. req.URL.RawQuery = targetQuery + req.URL.RawQuery
  18. } else {
  19. req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
  20. }
  21. if _, ok := req.Header["User-Agent"]; !ok {
  22. // explicitly disable User-Agent so it's not set to default value
  23. req.Header.Set("User-Agent", "")
  24. }
  25. }
  26. //超时处理
  27. transport := &http.Transport{
  28. Proxy: http.ProxyFromEnvironment,
  29. DialContext: (&net.Dialer{
  30. Timeout: 15 * time.Second, //连接超时
  31. KeepAlive: 15 * time.Second, //长连接超时时间
  32. DualStack: true,
  33. }).DialContext,
  34. MaxIdleConns: 30, //最大空闲连接
  35. IdleConnTimeout: 90 * time.Second, //空闲超时时间
  36. TLSHandshakeTimeout: 10 * time.Second, //tls握手超时时间
  37. ExpectContinueTimeout: 1 * time.Second, //100-continue 超时时间
  38. MaxIdleConnsPerHost: 300,
  39. }
  40. //异常处理
  41. //errFunc := func(w http.ResponseWriter, r *http.Request, err error) {
  42. // http.Error(w, "proxy error:", 500)
  43. // logs.GInfo.Error(r.Context(), err.Error())
  44. //}
  45. reverseProxy := &httputil.ReverseProxy{
  46. Director: director,
  47. Transport: transport,
  48. //ModifyResponse: change,
  49. ErrorHandler: errFunc}
  50. return reverseProxy
  51. }
  52. func singleJoiningSlash(a, b string) string {
  53. aslash := strings.HasSuffix(a, "/")
  54. bslash := strings.HasPrefix(b, "/")
  55. switch {
  56. case aslash && bslash:
  57. return a + b[1:]
  58. case !aslash && !bslash:
  59. return a + "/" + b
  60. }
  61. return a + b
  62. }