proxyClient.go 1.8 KB

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